Home  >  Article  >  PHP Framework  >  Learn about the middleware of ThinkPHP6.0 in one article

Learn about the middleware of ThinkPHP6.0 in one article

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼forward
2019-12-16 13:22:207565browse

Learn about the middleware of ThinkPHP6.0 in one article

ThinkPHP6.0 middleware is divided into system middleware and application middleware. System middleware is the middleware built into the core framework, and application middleware is the middleware created in the application.

The main application scenarios of middleware can include data filtering, permission detection, request interception and other behaviors for HTTP requests. Using middleware can make the definition of the controller simpler and handle many additional non-core business processes. All can be handed over to middleware for execution.

From the perspective of the scope of use of middleware, it can be divided into global middleware, application middleware, controller middleware and routing middleware.

Global middleware

Global middleware is the middleware defined in app\middleware.php. No middleware is enabled by default, but for supported system middleware The file is commented. You only need to uncomment to use the corresponding system middleware. The default content is as follows:

return [
    // 全局请求缓存
    // 'think\middleware\CheckRequestCache',
    // 多语言加载
    // 'think\middleware\LoadLangPack',
    // Session初始化
    // 'think\middleware\SessionInit',
    // 页面Trace调试
    // 'think\middleware\TraceDebug',
];

Some functions of the system are handed over to the middleware for unified management, including global request caching, multi-language Automatic detection and loading, Session initialization and page Trace debugging, that is to say, the application installed by default does not support Session. You must enable the Session initialization middleware globally before Session can take effect. For API applications, Session function support is not required.

You can add your application middleware in the global middleware definition file, but try to ensure that the system middleware is executed first. The middleware definition needs to use the complete class name, which can be quickly created through command line instructions. An application middleware:

php think make:middleware Test

will automatically generate an app\middleware\Test middleware class with the following content:

<?php
namespace app\middleware;
class Test
{
    public function handle($request, \Closure $next)
    {
    }
}

also supports the creation of middleware classes by specifying the complete namespace

php think make:middleware app\middleware\Hello

We add a test output

<?php
namespace app\middleware;
class Test
{
    public function handle($request, \Closure $next)
    {
    echo &#39;Before Middleware<br/>&#39;;
    $response = $next($request);
    echo &#39;After Middleware<br/>&#39;;
    return $response;
    }
}

The return value of the middleware handle method must be a Response object.

Then add

return [
\app\middleware\Test::class,
];

in the global middleware definition. Suppose the controller method we want to access is

<?php
namespace app\controller;
class Index
{
    public function hello()
    {
    return &#39;Hello,ThinkPHP!<br/>&#39;;
    }
}

The output of accessing the operation method is

Before Middleware
Hello,ThinkPHP!
After Middleware

You can see the execution process of middleware. From the execution process, it can be divided into pre-middleware and post-middleware. Of course, a middleware may have both pre- and post-behaviors. This is the case with the above Test middleware. . The code before $next($request) belongs to the pre-middleware category, and the code after it belongs to the post-middleware category.

Application middleware

If it is a multi-application mode, the application middleware is the middleware defined in app\application name\middleware.php and will only be used in It is valid under this application, and the definition format is consistent with the global middleware.

Routing middleware

Routing middleware means that a certain middleware will be executed only after the route is matched. It is defined using the middleware method in the route definition, for example:

Route::get(&#39;hello/:name&#39;,&#39;index/hello&#39;)
    ->middleware(\app\middleware\Hello::class);

You can define middleware for routing groups

Route::group(function(){
Route::get(&#39;hello/:name&#39;,&#39;index/hello&#39;);
//...
})->middleware(\app\middleware\Hello::class);

If you want to execute multiple middlewares, you can use

Route::group(function(){
Route::get(&#39;hello/:name&#39;,&#39;index/hello&#39;);
//...
})->middleware([\app\middleware\Hello::class,\app\middleware\Check::class]);

For frequently used middlewares, we can define one Alias, in the config\middleware.php configuration file, set

return [
&#39;hello&#39;=>\app\middleware\Hello::class,
&#39;check&#39;=>\app\middleware\Check::class,
];

The route definition can be changed to:

Route::group(function(){
Route::get(&#39;hello/:name&#39;,&#39;index/hello&#39;);
//...
})->middleware([&#39;hello&#39;,&#39;check&#39;]);

Supports defining aliases for a group of middleware

return [
&#39;test&#39;=>[\app\middleware\Hello::class,\app\middleware\Check::class],
];

Route definition It can be changed to

Route::group(function(){
Route::get(&#39;hello/:name&#39;,&#39;index/hello&#39;);
//...
})->middleware(&#39;test&#39;);

The middleware supports passing in a parameter. The middleware is defined as follows:

<?php
namespace app\middleware;
class Hello
{
    public function handle($request, \Closure $next, string $name = &#39;&#39;)
    {
    echo &#39;Hello&#39;. $name . &#39;<br/>&#39;;
    return $next($request);
    }
}

The name parameter can be passed in as the second parameter of the routing middleware

Route::get(&#39;hello/:name&#39;,&#39;index/hello&#39;)
    ->middleware(&#39;hello&#39;, &#39;middleware&#39;);

In addition to supporting parameters, you can use dependency injection in the handle method of middleware.

Controller middleware

Controller middleware only takes effect when accessing a certain controller

<?php
namespace app\controller;
class Hello
{
protected $middleware = [&#39;hello&#39;,&#39;check&#39;];
    public function index()
    {
    return &#39;Hello,ThinkPHP!<br/>&#39;;
    }
}

Since the middleware has been defined previously Aliases, so use the alias definition directly here, otherwise you have to use the full namespace definition.

By default, any operation method that the middleware defined in the controller accesses the controller will be executed. Sometimes you do not want all operations to need to execute middleware. There are two ways to define the middleware of the controller. Execution filtering of files.

<?php
namespace app\controller;
class Index
{
protected $middleware = [
&#39;hello&#39; => [&#39;only&#39;  => [&#39;hello&#39;]],
&#39;check&#39; => [&#39;except&#39;=> [&#39;hello&#39;]],
];
    public function hello()
    {
    return &#39;Hello,ThinkPHP!<br/>&#39;;
    }
    public function check()
    {
    return &#39;this action require check!<br/>&#39;;
    }    
}

The hello middleware will only be executed when the hello operation of the Index controller is executed, while the check middleware will be executed except for the hello method. You can actually test the specific effect.

Middleware Passing Parameters

There are many ways to pass parameters between middleware and controllers. A simple method is to use Request to pass parameters.

<?php
namespace app\middleware;
class Hello
{
    public function handle($request, \Closure $next)
    {
        $request->hello = &#39;ThinkPHP&#39;;
        
        return $next($request);
    }
}

The middleware's parameter transfer to the controller must be completed in the pre-middleware. The controller cannot receive the parameters passed by the post-middleware to the controller.

Then you can use it directly in the controller method

public function index(Request $request)
{
return $request->hello; // ThinkPHP
}

Many ThinkPHP tutorial videos are available on the PHP Chinese website. Welcome to learn online!

This article is reproduced from: https://www.php.cn/phpkj/thinkphp/

The above is the detailed content of Learn about the middleware of ThinkPHP6.0 in one article. For more information, please follow other related articles on the PHP Chinese website!

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