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 'Before Middleware<br/>'; $response = $next($request); echo 'After Middleware<br/>'; 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 'Hello,ThinkPHP!<br/>'; } }
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('hello/:name','index/hello') ->middleware(\app\middleware\Hello::class);
You can define middleware for routing groups
Route::group(function(){ Route::get('hello/:name','index/hello'); //... })->middleware(\app\middleware\Hello::class);
If you want to execute multiple middlewares, you can use
Route::group(function(){ Route::get('hello/:name','index/hello'); //... })->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 [ 'hello'=>\app\middleware\Hello::class, 'check'=>\app\middleware\Check::class, ];
The route definition can be changed to:
Route::group(function(){ Route::get('hello/:name','index/hello'); //... })->middleware(['hello','check']);
Supports defining aliases for a group of middleware
return [ 'test'=>[\app\middleware\Hello::class,\app\middleware\Check::class], ];
Route definition It can be changed to
Route::group(function(){ Route::get('hello/:name','index/hello'); //... })->middleware('test');
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 = '') { echo 'Hello'. $name . '<br/>'; return $next($request); } }
The name parameter can be passed in as the second parameter of the routing middleware
Route::get('hello/:name','index/hello') ->middleware('hello', 'middleware');
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 = ['hello','check']; public function index() { return 'Hello,ThinkPHP!<br/>'; } }
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 = [ 'hello' => ['only' => ['hello']], 'check' => ['except'=> ['hello']], ]; public function hello() { return 'Hello,ThinkPHP!<br/>'; } public function check() { return 'this action require check!<br/>'; } }
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 = 'ThinkPHP'; 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to implement custom middleware in CodeIgniter Introduction: In modern web development, middleware plays a vital role in applications. They can be used to perform some shared processing logic before or after the request reaches the controller. CodeIgniter, as a popular PHP framework, also supports the use of middleware. This article will introduce how to implement custom middleware in CodeIgniter and provide a simple code example. Middleware overview: Middleware is a kind of request

Implementing user authentication using middleware in the Slim framework With the development of web applications, user authentication has become a crucial feature. In order to protect users' personal information and sensitive data, we need a reliable method to verify the user's identity. In this article, we will introduce how to implement user authentication using the Slim framework’s middleware. The Slim framework is a lightweight PHP framework that provides a simple and fast way to build web applications. One of the powerful features is the middle

The principle of tomcat middleware is implemented based on Java Servlet and Java EE specifications. As a Servlet container, Tomcat is responsible for processing HTTP requests and responses and providing the running environment for Web applications. The principles of Tomcat middleware mainly involve: 1. Container model; 2. Component architecture; 3. Servlet processing mechanism; 4. Event listening and filters; 5. Configuration management; 6. Security; 7. Clustering and load balancing; 8. Connector technology; 9. Embedded mode, etc.

How to use middleware to handle form validation in Laravel, specific code examples are required Introduction: Form validation is a very common task in Laravel. In order to ensure the validity and security of the data entered by users, we usually verify the data submitted in the form. Laravel provides a convenient form validation function and also supports the use of middleware to handle form validation. This article will introduce in detail how to use middleware to handle form validation in Laravel and provide specific code examples.

How to use middleware for data acceleration in Laravel Introduction: When developing web applications using the Laravel framework, data acceleration is the key to improving application performance. Middleware is an important feature provided by Laravel that handles requests before they reach the controller or before the response is returned. This article will focus on how to use middleware to achieve data acceleration in Laravel and provide specific code examples. 1. What is middleware? Middleware is a mechanism in the Laravel framework. It is used

How to use middleware for response conversion in Laravel Middleware is one of the very powerful and practical features in the Laravel framework. It allows us to process requests and responses before the request enters the controller or before the response is sent to the client. In this article, I will demonstrate how to use middleware for response transformation in Laravel. Before starting, make sure you have Laravel installed and a new project created. Now we will follow these steps: Create a new middleware Open

Laravel is a popular PHP web application framework that provides many fast and easy ways to build efficient, secure and scalable web applications. When developing Laravel applications, we often need to consider the issue of data recovery, that is, how to recover data and ensure the normal operation of the application in the event of data loss or damage. In this article, we will introduce how to use Laravel middleware to implement data recovery functions and provide specific code examples. 1. What is Lara?

How to set up Cross-Origin Resource Sharing (CORS) using middleware in the Slim framework Cross-Origin Resource Sharing (CORS) is a mechanism that allows the server to set some additional information in the HTTP response header to tell the browser whether Allow cross-domain requests. In some projects with front-end and back-end separation, the CORS mechanism can be used to realize the front-end's cross-domain request for the back-end interface. When using the Slim framework to develop REST API, we can use middleware (Middleware)
