Starting from version 5.1.6, middleware support is officially introduced.
Middleware is mainly used to intercept or filter application HTTP requests and perform necessary business processing.
Define middleware
You can quickly generate middleware through command line instructions
php think make:middleware Check
This instruction will generate a Check under the application/http/middleware directory middleware.
<?php namespace app\http\middleware; class Check { public function handle($request, \Closure $next) { if ($request->param('name') == 'think') { return redirect('index/think'); } return $next($request); } }
The entry execution method of middleware must be the handle method, and the first parameter is the Request object, and the second parameter is a closure.
The return value of the middleware handle method must be a Response object.
In this middleware, we perform redirection processing when we judge that the name parameter of the current request is equal to think. Otherwise, the request will be passed further to the application. To continue passing the request to the application, simply call the callback function $next with $request as argument.
Under certain requirements, you can use the third parameter to pass in additional parameters.
<?php namespace app\http\middleware; class Check { public function handle($request, \Closure $next, $name) { if ($name == 'think') { return redirect('index/think'); } return $next($request); } }
Pre/post middleware
Whether the middleware is executed before or after the specific operation is requested depends entirely on the definition of the middleware itself.
The following is a middleware for pre-behavior
<?php namespace app\http\middleware; class Before { public function handle($request, \Closure $next) { // 添加中间件执行代码 return $next($request); } }
The following is a middleware for post-behavior
<?php namespace app\http\middleware; class After { public function handle($request, \Closure $next) { $response = $next($request); // 添加中间件执行代码 return $response; } }
Let’s take a more practical example. We need to determine the current browsing The server environment is WeChat or Alipay
namespace app\http\middleware; /** * 访问环境检查,是否是微信或支付宝等 */ class InAppCheck { public function handle($request, \Closure $next) { if (preg_match('~micromessenger~i', $request->header('user-agent'))) { $request->InApp = 'WeChat'; } else if (preg_match('~alipay~i', $request->header('user-agent'))) { $request->InApp = 'Alipay'; } return $next($request); } }
Then add a middleware.php file in your mobile version module
For example: /path/application/mobile/middleware.php
return [ app\http\middleware\InAppCheck::class, ];
Then in your controller you can get the relevant value through $this->request->InApp
Register middleware
Routing middleware
The most commonly used middleware registration method is to register routing middleware
Route::rule('hello/:name','hello') ->middleware('Auth');
or use the complete middleware class name
Route::rule('hello/:name','hello') ->middleware(app\http\middleware\Auth::class);
Supports multiple registrations Middleware
Route::rule('hello/:name','hello') ->middleware(['Auth', 'Check']);
V5.1.7 version, you can directly predefine the middleware in middleware.php in the application configuration directory (actually adding an alias identifier), for example:
return [ 'auth'=>app\http\middleware\Auth::class, 'check'=>app\http\middleware\Check::class ];
Then Register directly using middleware aliases in routing
Route::rule('hello/:name','hello') ->middleware(['auth', 'check']);
Starting from V5.1.8, you can use aliases to define a set of middleware, for example:
return [ 'check'=>[ app\http\middleware\Auth::class, app\http\middleware\Check::class ], ];
Then, directly use the following method to register the middleware File
Route::rule('hello/:name','hello') ->middleware('check');
Supports the registration of middleware for routing groups
Route::group('hello', function(){ Route::rule('hello/:name','hello'); })->middleware('Auth');
V5.1.8 version starts to support the registration of middleware for a certain domain name
Route::domain('admin', function(){ // 注册域名下的路由规则 })->middleware('Auth');
If you need to pass in additional parameters to the middleware For files, you can use
Route::rule('hello/:name','hello') ->middleware('Auth:admin');
If you use constant definition, you can pass in the middleware parameters in the second parameter.
Route::rule('hello/:name','hello') ->middleware(Auth::class, 'admin');
If you need to define multiple middlewares, use the array method
Route::rule('hello/:name','hello') ->middleware([Auth::class, 'Check']);
You can pass in the same additional parameter
Route::rule('hello/:name','hello') ->middleware([Auth::class, 'Check'], 'admin');
or specify the middleware parameters individually.
Route::rule('hello/:name','hello') ->middleware(['Auth:admin', 'Check:editor']);
Use closures to define middleware
You don’t have to use middleware classes. In some simple situations, you can use closures to define middleware, but The closure function must return a Response object instance.
Route::group('hello', function(){ Route::rule('hello/:name','hello'); })->middleware(function($request,\Closure $next){ if ($request->param('name') == 'think') { return redirect('index/think'); } return $next($request); });
Global middleware
You can define the middleware.php file under the application directory and use the following method:
<?php return [ \app\http\middleware\Auth::class, 'Check', 'Hello', ];
Registration of middleware The full class name should be used, or app\http\middleware as the namespace if no namespace is specified.
The execution order of global middleware is the definition order. Middleware parameters can be passed in when defining global middleware, and two methods are supported.
<?php return [ [\app\http\middleware\Auth::class, 'admin'], 'Check', 'Hello:thinkphp', ];
The above definition means that the admin parameter is passed to the Auth middleware and the thinkphp parameter is passed to the Hello middleware.
Module middleware
Starting from version V5.1.8, module middleware definition is supported. You can add the middleware.php file directly under the module directory, definition method and application The middleware definition is the same, but it will only take effect under this module.
Controller middleware
Starting from V5.1.17, it is supported to define middleware for controllers. First, your controller needs to inherit the system's think\Controller class, and then define the middleware attribute in the controller, for example:
<?php namespace app\index\controller; use think\Controller; class Index extends Controller { protected $middleware = ['Auth']; public function index() { return 'index'; } public function hello() { return 'hello'; } }
When the index controller is executed, the Auth middleware will be called. It also supports the use of complete namespace definition.
If you need to set the effective operation in the middle of the controller, you can define it as follows:
<?php namespace app\index\controller; use think\Controller; class Index extends Controller { protected $middleware = [ 'Auth' => ['except' => ['hello'] ], 'Hello' => ['only' => ['hello'] ], ]; public function index() { return 'index'; } public function hello() { return 'hello'; } }
The middleware passes parameters to the controller
You can pass the request Pass parameters to the controller (or other places) by object assignment, such as
<?php namespace app\http\middleware; class Hello { public function handle($request, \Closure $next) { $request->hello = 'ThinkPHP'; return $next($request); } }
Note that the variable name passed should not conflict with the param variable.
Then you can use it directly in the controller method
public function index(Request $request) { return $request->hello; // ThinkPHP }
This article comes from the ThinkPHP framework technical article column: http://www.php.cn/phpkj/thinkphp/
The above is the detailed content of What does thinkphp middleware mean?. For more information, please follow other related articles on the PHP Chinese website!