Home  >  Article  >  PHP Framework  >  What does thinkphp middleware mean?

What does thinkphp middleware mean?

藏色散人
藏色散人Original
2019-06-29 13:31:003407browse

What does thinkphp middleware mean?

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(&#39;name&#39;) == &#39;think&#39;) {
            return redirect(&#39;index/think&#39;);
        }
        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 == &#39;think&#39;) {
            return redirect(&#39;index/think&#39;);
        }
        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(&#39;~micromessenger~i&#39;, $request->header(&#39;user-agent&#39;))) {
            $request->InApp = &#39;WeChat&#39;;
        } else if (preg_match(&#39;~alipay~i&#39;, $request->header(&#39;user-agent&#39;))) {
            $request->InApp = &#39;Alipay&#39;;
        }
        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(&#39;hello/:name&#39;,&#39;hello&#39;)
->middleware(&#39;Auth&#39;);

or use the complete middleware class name

Route::rule(&#39;hello/:name&#39;,&#39;hello&#39;)
->middleware(app\http\middleware\Auth::class);

Supports multiple registrations Middleware

Route::rule(&#39;hello/:name&#39;,&#39;hello&#39;)
->middleware([&#39;Auth&#39;, &#39;Check&#39;]);

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 [
&#39;auth&#39;=>app\http\middleware\Auth::class,
    &#39;check&#39;=>app\http\middleware\Check::class
];

Then Register directly using middleware aliases in routing

Route::rule(&#39;hello/:name&#39;,&#39;hello&#39;)
->middleware([&#39;Auth&#39;, &#39;Check&#39;]);

Starting from V5.1.8, you can use aliases to define a set of middleware, for example:

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

Then, directly use the following method to register the middleware File

Route::rule(&#39;hello/:name&#39;,&#39;hello&#39;)
->middleware(&#39;check&#39;);

Supports the registration of middleware for routing groups

Route::group(&#39;hello&#39;, function(){
Route::rule(&#39;hello/:name&#39;,&#39;hello&#39;);
})->middleware(&#39;Auth&#39;);

V5.1.8 version starts to support the registration of middleware for a certain domain name

Route::domain(&#39;admin&#39;, function(){
// 注册域名下的路由规则
})->middleware(&#39;Auth&#39;);

If you need to pass in additional parameters to the middleware For files, you can use

Route::rule(&#39;hello/:name&#39;,&#39;hello&#39;)
->middleware(&#39;Auth:admin&#39;);

If you use constant definition, you can pass in the middleware parameters in the second parameter.

Route::rule(&#39;hello/:name&#39;,&#39;hello&#39;)
->middleware(Auth::class, &#39;admin&#39;);

If you need to define multiple middlewares, use the array method

Route::rule(&#39;hello/:name&#39;,&#39;hello&#39;)
->middleware([Auth::class, &#39;Check&#39;]);

You can pass in the same additional parameter

Route::rule(&#39;hello/:name&#39;,&#39;hello&#39;)
->middleware([Auth::class, &#39;Check&#39;], &#39;admin&#39;);

or specify the middleware parameters individually.

Route::rule(&#39;hello/:name&#39;,&#39;hello&#39;)
->middleware([&#39;Auth:admin&#39;, &#39;Check:editor&#39;]);

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(&#39;hello&#39;, function(){
Route::rule(&#39;hello/:name&#39;,&#39;hello&#39;);
})->middleware(function($request,\Closure $next){
    if ($request->param(&#39;name&#39;) == &#39;think&#39;) {
        return redirect(&#39;index/think&#39;);
    }
    
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,
    &#39;Check&#39;,
    &#39;Hello&#39;,
];

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, &#39;admin&#39;],
    &#39;Check&#39;,
    &#39;Hello:thinkphp&#39;,
];

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 = [&#39;Auth&#39;];
    public function index()
    {
        return &#39;index&#39;;
    }
    public function hello()
    {
        return &#39;hello&#39;;
    }
}

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 = [ 
    &#39;Auth&#39; => [&#39;except&#39; => [&#39;hello&#39;] ],
        &#39;Hello&#39; => [&#39;only&#39; => [&#39;hello&#39;] ],
    ];
    public function index()
    {
        return &#39;index&#39;;
    }
    public function hello()
    {
        return &#39;hello&#39;;
    }
}

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 = &#39;ThinkPHP&#39;;
        
        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!

Statement:
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
Previous article:How to install thinkphpNext article:How to install thinkphp