ThinkPHP6 project basic operation (14. The actual part of the middleware processing login process)

One, define middleware

<?php

namespace app\middleware;

class Check
{
    
    
    public function handle($request, \Closure $next)
    {
    
    
        if ($request->param('name') == 'think') {
    
    
            return redirect('index/think');
        }

        return $next($request);
    }
}

The middleware class can be named arbitrarily, the entry execution method of the middleware must be a handlemethod, and the first parameter is an Requestobject, and the second parameter is one 闭包.

Two, 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 with pre-behavior:

<?php

namespace app\middleware;

class Before
{
    
    
    public function handle($request, \Closure $next)
    {
    
    
        // 添加中间件执行代码

        return $next($request);
    }
}

The following is a middleware with post-behavior:

<?php

namespace app\middleware;

class After
{
    
    
    public function handle($request, \Closure $next)
    {
    
    
		$response = $next($request);

        // 添加中间件执行代码

        return $response;
    }
}

Three, register middleware

The new middleware is divided into 全局中间件, 应用中间件(多应用模式下有效), 路由中间件and 控制器中间件four groups. The order of execution is:

Global Middleware -> Application Middleware -> Routing Middleware -> Controller Middleware

1. Global Middleware

Global middleware is defined in the file under the appdirectory middleware.php, using the following method:

<?php

return [
	\app\middleware\Auth::class
];

The registration of middleware should use the complete class name, if the middleware alias (or group) has been defined, it can be used directly. The execution order of the global middleware is the definition order.

2. Application Middleware

If you use the multi-application mode, application middleware definition is supported. You can directly add middleware.phpfiles under the application directory . The definition method is the same as the global middleware definition, but it will only take effect under the application.

3. Routing Middleware

The most commonly used middleware registration method is to register routing middleware:

Route::rule('hello/:name','hello')->middleware(\app\middleware\Auth::class);

Support registration of multiple middleware:

Route::rule('hello/:name','hello')->middleware([\app\middleware\Auth::class, \app\middleware\Check::class]);

4. Controller middleware

Support to define middleware for the controller, only need to define middlewareattributes in the controller , for example:

<?php
namespace app\controller;

class Index
{
    
    
    protected $middleware = ['auth'];

    public function index()
    {
    
    
        return 'index';
    }

    public function hello()
    {
    
    
        return 'hello';
    }
}

The authmiddleware will be called when the index controller is executed , and the full namespace definition is also supported.

5. Built-in middleware

Middleware description
think\middleware\AllowCrossDomain Cross-domain request support
think\middleware\CheckRequestCache Request cache
think\middleware\LoadLangPack Multilingual loading
think\middleware\SessionInit Session initialization
think\middleware\FormTokenCheck Form token

These built-in middlewares are not defined by default. You can middleware.phpdefine these middlewares in the application files, routes, or controllers. If you don't need to use them, just cancel the definitions.

Fourth, middleware use-background login page jump process

Insert picture description here
When accessing the background homepage, if you have logged in (session has been recorded), you can enter the attention, otherwise you can return to the login page; if you access the background login page, if you have logged in (session has been recorded), you will directly jump to the homepage, otherwise you will enter the login page .

1. Create Auth middleware

adminCreate a middlewarefolder in the application folder and create a Auth.phpmiddleware file:

<?php

namespace app\admin\middleware;
use think\Response;

class Auth
{
    
    
    public function handle($request, \Closure $next){
    
    
        // 前置中间件
        if(empty(session(config("admin.session_admin"))) && !preg_match("/login/",$request->pathinfo()) ){
    
    
            return redirect(url('login/index'));
        }
        if(!empty(session(config("admin.session_admin"))) && preg_match("/login\/index/",$request->pathinfo())){
    
    
            return redirect(url('index/index'));
        }

        $response = $next($request);
        // 后置中间件
        return $response;
    }

    public function end(Response $response){
    
    

    }
}

admin.session_adminIt is defined in the configuration file under the admin/config folder:
admin/config/admin.php

<?php
return [
    'session_admin' => 'adminUser'
];

2. Register application middleware

adminCreate a new in the application directory middleware.php:

<?php
return [
    \think\middleware\SessionInit::class,
    app\admin\middleware\Auth::class
];

Guess you like

Origin blog.csdn.net/zy1281539626/article/details/110881356