Home > PHP Framework > ThinkPHP > How to use middleware for request processing in ThinkPHP6?

How to use middleware for request processing in ThinkPHP6?

WBOY
Release: 2023-06-12 12:25:40
Original
2460 people have browsed it

In ThinkPHP6, middleware is a commonly used request processing tool. Through middleware, we can easily process requests to implement permission control, logging, request verification and other functions, improving the security and maintainability of applications. This article will introduce how to use middleware for request processing in ThinkPHP6.

1. What is middleware

Middleware is an independent request handler that can intercept requests sent by the client and process them. In ThinkPHP6, middleware is designed based on the PSR-15 specification. Through middleware, we can pre-process or post-process requests to implement some common functions, such as login verification, permission control, request filtering, response processing, etc. .

2. Use of ThinkPHP6 middleware

  1. Create middleware

In ThinkPHP6, you can quickly create middleware through command line tools. Use the following command to create a middleware named CheckAuth in the app/middleware directory.

php think make:middleware CheckAuth
Copy after login

The created CheckAuth middleware class is as follows:

<?php

namespace appmiddleware;

class CheckAuth
{
    public function handle($request, Closure $next)
    {
        // 执行中间件操作

        return $next($request);
    }
}
Copy after login

In the above code, the middleware class must contain the handle method. The handle method accepts two parameters: $request and $next, where $request is the request object and $next is the processing method of the next middleware or controller. In the handle method, we can perform some preprocessing on the $request object, and then use return $next($request) to call the processing method of the next middleware or controller.

  1. Register middleware

After creating the middleware, you need to register it in the application. In ThinkPHP6, middleware can be registered through application configuration, route definition, and controller annotation.

2.1 Application configuration

You can configure global middleware or set middleware on demand in the application's configuration file config/app.php.

// 全局中间件
'middleware' => [
    appmiddlewareCheckAuth::class,
],

// 按需设置中间件
'route' => [
    // Route::group 也支持
    'blog/detail' => ['appmiddlewareCheckAuth'],
]
Copy after login

In the above code, middleware can be globally registered using the middleware configuration item. The class name of each middleware is separated by commas. In the route configuration item, middleware can be specified for different routes.

2.2 Route definition

You can specify middleware in the Route::rule method or Route::group method.

use thinkacadeRoute;

Route::rule('blog/detail', 'blog/detail', 'GET')->middleware('appmiddlewareCheckAuth');
Copy after login

In the above code, we added the middleware method to specify the middleware when calling the Route::rule method.

2.3 Controller annotations

You can specify middleware in controller annotations.

namespace appcontroller;

/**
 * @middleware(appmiddlewareCheckAuth::class)
 */
class Blog
{
    public function detail()
    {
        // 控制器的处理逻辑
    }
}
Copy after login

In the above code, we added the middleware attribute to the controller annotation to specify the middleware.

  1. Execution order of middleware

In ThinkPHP6, middleware is executed in the order of registration, first registered and executed, and then registered and executed.

In application configuration and controller annotations, we can use the Middleware::class method to specify the execution order of middleware. As shown below:

// 全局中间件按照顺序执行
'middleware' => [
    appmiddlewareLog::class,
    appmiddlewareCheckAuth::class,
],

// 按需设置中间件按照顺序执行
'route' => [
    'blog/detail' => ['appmiddlewareLog', 'appmiddlewareCheckAuth']
],

// 控制器注解中间件按照顺序执行
namespace appcontroller;

/**
 * @middleware([appmiddlewareLog::class, appmiddlewareCheckAuth::class])
 */
class Blog
{
    public function detail()
    {
        // 控制器的处理逻辑
    }
}
Copy after login

In the above code, we specified the Middleware::class method in the order of middleware registration.

  1. Parameter passing of middleware

Middleware can share data through parameter passing. In the handle method, we can add properties, methods or parameters to the $request object, and then pass the $request object to the next middleware or controller to achieve data sharing.

For example, in the following example, we define the attribute $name in the first middleware and pass it to the second middleware and controller so that they can use the attribute.

<?php

namespace appmiddleware;

class CheckAuth
{
    public function handle($request, Closure $next, $name)
    {
        $request->name = $name;

        return $next($request);
    }
}

class Log
{
    public function handle($request, Closure $next)
    {
        echo 'name:' . $request->name . '<br>';
        return $next($request);
    }
}

namespace appcontroller;

class Blog
{
    public function detail(Request $request)
    {
        echo 'name:' . $request->name . '<br>';
        // 控制器的处理逻辑
    }
}

// 路由配置文件
use thinkacadeRoute;

Route::rule('blog/detail', 'blog/detail', 'GET')
->middleware(['appmiddlewareCheckAuth:name', 'appmiddlewareLog']);
Copy after login

In the above code, we define the $name attribute in the handle method of the CheckAuth class and save it in the $request object. In both the handle method of the Log class and the Blog controller, we can access this property through the $request object.

In the route definition, we use the parameter passing function of the middleware to pass the parameter name to the CheckAuth middleware. In the settings of on-demand middleware, you can also use the Middleware::class method to specify middleware parameters.

5. Summary

Middleware is a commonly used request processing tool that can pre-process or post-process client requests before and after the request. In ThinkPHP6, middleware is designed based on the PSR-15 specification. Through middleware, we can easily implement functions such as permission control, logging, and request verification. Middleware is executed in the order in which it is registered, and data can be shared between middleware through parameter passing. Through the flexible use of middleware, we can improve the security, maintainability and scalability of applications.

The above is the detailed content of How to use middleware for request processing in ThinkPHP6?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template