This article mainly introduces two tips for PHP framework Laravel. This article explains batch naming of routes in Route::controller, Two tips for judging the current operating environment based on system variables. Friends who need it can refer to it
I have been using Laravel as a PHP development framework for a long time, but there are some places that are not covered in the official documents, and I forget them every once in a while. I did some simple organizing recently and took notes on it.
1. Route::controller route naming:
Using Route::controller can reduce a lot of work in route customization, but sometimes it is necessary to name a specific route for use, but the Route::controller method batches the routes for all methods in a Controller. This How to name it? You can use the third parameter in controller($uri, $controller, $names = array()). This is an array. The key of the array is the method, and the value of the array is the name.
The code is as follows:
// Signature of this function:
Public function controller($uri, $controller, $names = array())
// Generally used without naming:
Route::controller('admin', 'AdminController');
// If you need to name some of the methods:
Route::controller('admin', 'AdminController', array(
'getIndex' => 'admin.index',
'getLogin' => 'admin.login',
'postLogin' => 'admin.login'
));
2. Determine the current operating environment based on system variables
The system's default method of determining whether it is a local environment is to specify a set of host names as the local environment in the 'local' array. For example, if you are doing development on an office computer or Macbook, you need to add the two host names. I think it’s very troublesome to write everything down. It was changed to judge based on $_SERVER['LARAVEL_ENV'], so that I can define the environment variable of 'LARAVEL_ENV' in all development machines with the value of 'local', so the development machine will automatically recognize it as the 'local' environment. , and 'production' in other cases.
The code is as follows:
// The default way of writing is to determine whether it is a local environment based on the host name
$env = $app->detectEnvironment(array(
'local' => array('homestead');
));
// Modified to first determine whether the system variable is specified, and then determine the host name if not
$env = $app->detectEnvironment(function(){
$_env = getenv('LARAVEL_ENV') ? getenv('LARAVEL_ENV') : array(
'local' => array('homestead')
);
return $_env;
});
// This is actually to read the value of $_SERVER['LARAVEL_ENV']
// In Apache, you can use SetEnv to set,
// In Nginx, you can use fastcgi_param to set