Home > PHP Framework > ThinkPHP > body text

what is thinkphp middleware

藏色散人
Release: 2019-07-04 13:30:59
Original
7802 people have browsed it

ThinkPHP was born to simplify enterprise-level application development and agile WEB application development. It was first born in early 2006, and was officially renamed ThinkPHP on New Year's Day 2007, and was released under the Apache2 open source agreement. ThinkPHP has been adhering to the simple and practical design principle since its birth. While maintaining excellent performance and minimal code, it also focuses on ease of use. And it has many original functions and features. With the active participation of the community team, it is continuously optimized and improved in terms of ease of use, scalability and performance.

what is thinkphp middleware

#What is thinkphp middleware?

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
Copy after login

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);
    }
}
Copy after login

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);
    }
}
Copy after login

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);
    }
}
Copy after login

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;
    }
}
Copy after login

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);
    }
}
Copy after login

Then add a middleware.php file in your mobile version module

For example: /path/application/mobile/middleware.php

return [
    app\http\middleware\InAppCheck::class,
];
Copy after login

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;);
Copy after login

or use the complete middleware class name

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

Supports multiple registrations Middleware

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

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
];
Copy after login

Then Register directly using middleware aliases in routing

Route::rule(&#39;hello/:name&#39;,&#39;hello&#39;)
->middleware([&#39;auth&#39;, &#39;check&#39;]);
Copy after login

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
    ],
];
Copy after login

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

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

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;);
Copy after login

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;);
Copy after login

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;);
Copy after login

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;);
Copy after login

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;]);
Copy after login

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;);
Copy after login

or specify the middleware parameters individually.

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

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);
});
Copy after login

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;,
];
Copy after login

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;,
];
Copy after login

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;;
    }
}
Copy after login

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;;
    }
}
Copy after login

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);
    }
}
Copy after login

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
}
Copy after login

本文来自ThinkPHP框架技术文章栏目:http://www.php.cn/phpkj/thinkphp/

The above is the detailed content of what is thinkphp middleware. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!