Home  >  Article  >  PHP Framework  >  Thinkphp5.1 explains the usage of middleware in detail

Thinkphp5.1 explains the usage of middleware in detail

WBOY
WBOYforward
2022-04-24 11:56:104135browse

This article brings you relevant knowledge about thinkphp, which mainly introduces the usage of middleware, including what is pre-middleware, post-middleware, and routing Middleware, global middleware and other related content, let's take a look at it together, I hope it will be helpful to everyone.

Thinkphp5.1 explains the usage of middleware in detail

## Recommended study: "

PHP Video Tutorial"

1. The role of middleware

Middleware is mainly used to intercept or filter

HTTP requests of applications and perform necessary business processing. For example, middleware can be used to check whether the user's request information contains a one-sentence Trojan.

The difference between behavioral hooks and middleware:

Middleware: It processes project requests. When the user visits us project, the middleware can determine whether the user has permission for this request, or determine whether the user has illegal access;

Behavior hook: When an action starts or ends Methods that will be triggered, such as logging successful user registration;

Middleware processes user requests, while hooks process user actions. Middleware is equivalent to a filter, and hooks are equivalent to events. It adopts AOP thinking.

2. Define middleware

First, you can quickly generate middleware through the cmd command line command. Execute the following cmd command in the root directory of the project:

php think make:middleware Check
This command will generate a

Check middleware under the application/http/middleware directory. The code is as follows:

<?php

namespace app\http\middleware;

class Check
{
    public function handle($request, \Closure $next)
    {
        if ($request->param('name') == 'index') {
            return redirect('/');//重定向到首页
        }

        return $next($request);//返回的是一个Response对象
    }
}

Middleware description:

1. The entry execution method of middleware must be the

handle method, and the first parameter is the Request object, and the second Each parameter is a closure;

2. Middleware The return value of the

handle method must be a Response object;

3. Middleware You can directly use the Request object to obtain the request parameters;

4. Under certain requirements, you can use the third parameter to pass in additional parameters;

public function handle($request, \Closure $next, $name){
    if ($name == 'index') {
        return redirect('/');//重定向到首页
    }

    return $next($request);
}
1. Before Pre-middleware

Pre-middleware means that the middleware code is executed before the http request is completed.

<?php

namespace app\http\middleware;

class Before
{
    public function handle($request, \Closure $next)
    {
        // 先执行中间件代码
        return $next($request);
    }
}

2. Post-middleware

Post-middleware means that the middleware code starts to be executed after the http request is completed.

<?php

namespace app\http\middleware;

class After
{
    public function handle($request, \Closure $next)
    {
		$response = $next($request);
        //后执行中间件代码
        return $response;
    }
}

3. Registration middleware

1. Routing middleware

As the name suggests, it is specified under a certain route This middleware will be called, that is, when the user accesses this routing link, this middleware will be executed.

//用户登录的路由
Route::rule(&#39;login&#39;,&#39;index/User/login&#39;)->middleware('Auth');
Or use the complete middleware class name:

Route::rule('login','index/User/login')->middleware(app\http\middleware\Auth::class);

Note: It is recommended to use the complete class name for middleware registration, if no namespace is specified By default, app\http\middleware is used as the namespace

The same route also supports the registration of multiple middlewares, which only need to be separated by commas in middleware():

Route::rule('login','index/User/login')->middleware(['Auth', 'Check']);
After the Thinkphp5.1.8 version, it supports registering middleware for routing groups, as follows:

//一个名为user的路由分组
Route::group('user', function(){
	Route::rule('login','index/User/login');
    Route::rule('register','index/User/register');
})->middleware('Auth');
2. Global middleware

means, all (global) HTTP access requests will automatically call this middleware.

Create the

middleware.php file in the application directory. The code is as follows:

<?php
return [
    //第1个中间件
	\app\http\middleware\Auth::class,
    //第2个中间件(Check中间件没有指定命名空间,所以会默认使用app\http\middleware作为命名空间)
    &#39;Check&#39;,
];

3. Module middleware

Thinkphp5.1.8 Versions and above support module middleware definition. You can add the middleware.php file directly under the module directory. The definition method is the same as the global middleware definition, but it will only be in this module. The following takes effect.

4. Controller middleware

Thinkphp5.1.17 version or above supports defining middleware for the controller. 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 = [&#39;Auth&#39;];

    public function index()
    {
        return &#39;index&#39;;
    }
}

5. Use closure definition Middleware

In some simple situations, we do not need to use middleware classes. At this time, we can use closures to define middleware, but the closure function must return a

Response object instance.

Route::group(&#39;hello&#39;, function(){
	Route::rule(&#39;login&#39;,&#39;index/User/login&#39;);
})->middleware(function($request,\Closure $next){
    if ($request->param('name') == 'index') {
        return redirect('/');//重定向到首页
    }    
	return $next($request);
});

4. Pass parameters to the middleware

1. Pass parameters to the global middleware

<?php
return [
	[\app\http\middleware\Auth::class, &#39;张三&#39;],
    &#39;Check:李四&#39;,
];

上面的定义表示给Auth中间件传入参数为张三,给Check中间件传入参数为李四

2、路由中间件传参数

(1)、给Auth中间件传入参数张三

Route::rule(&#39;login&#39;,&#39;index/User/login&#39;)->middleware('Auth:张三');

 也可以这样写:

Route::rule('login','index/User/login')->middleware(Auth::class, '张三');

(2)、给多个中间件传入同一个参数 

Route::rule('login','index/User/login')->middleware([Auth::class, 'Check'], '张三');

(3)、单独指定各个中间件的参数

Route::rule('login','index/user/login')->middleware(['Auth:张三', 'Check:李四']);

五、中间件向控制器传参数

前面讲的给中间件传入特定的参数 (常量),那么中间要如何向控制器传入参数呢?我们可以通过给Request请求对象赋值的方式传参给控制器(或者其它地方),例如:

<?php
namespace app\http\middleware;

class Auth
{
    public function handle($request, \Closure $next)
    {
        //给控制器传参数
        $request->result = '验证成功';       
        return $next($request);
    }
}

需要特别注意:传递的变量名称不要和Request已有的参数变量名有冲突,比如用户登录请求的Request参数里已经有一个username,那么中间件向控制器传参,就不能再用这个username了,否则会改变原来参数的值。

然后在控制器的方法里面可以直接使用:

public function index(Request $request)
{
	return $request->result;
}

推荐学习:《PHP视频教程

The above is the detailed content of Thinkphp5.1 explains the usage of middleware in detail. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete