Home PHP Framework ThinkPHP What does thinkphp middleware mean?

What does thinkphp middleware mean?

Jun 29, 2019 pm 01:31 PM
thinkphp

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
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
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
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

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 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

How is the performance of thinkphp? How is the performance of thinkphp? Apr 09, 2024 pm 05:24 PM

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

ThinkPHP6 backend management system development: realizing backend functions ThinkPHP6 backend management system development: realizing backend functions Aug 27, 2023 am 11:55 AM

ThinkPHP6 backend management system development: Implementing backend functions Introduction: With the continuous development of Internet technology and market demand, more and more enterprises and organizations need an efficient, safe, and flexible backend management system to manage business data and conduct operational management. This article will use the ThinkPHP6 framework to demonstrate through examples how to develop a simple but practical backend management system, including basic functions such as permission control, data addition, deletion, modification and query. Environment preparation Before starting, we need to install PHP, MySQL, Com

See all articles