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('name') == 'think') { return redirect('index/think'); } 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 == 'think') { return redirect('index/think'); } 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('~micromessenger~i', $request->header('user-agent'))) { $request->InApp = 'WeChat'; } else if (preg_match('~alipay~i', $request->header('user-agent'))) { $request->InApp = 'Alipay'; } 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('hello/:name','hello') ->middleware('Auth');
or use the complete middleware class name
Route::rule('hello/:name','hello') ->middleware(app\http\middleware\Auth::class);
Supports multiple registrations Middleware
Route::rule('hello/:name','hello') ->middleware(['Auth', 'Check']);
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 [ 'auth'=>app\http\middleware\Auth::class, 'check'=>app\http\middleware\Check::class ];
Then Register directly using middleware aliases in routing
Route::rule('hello/:name','hello') ->middleware(['Auth', 'Check']);
Starting from V5.1.8, you can use aliases to define a set of middleware, for example:
return [ 'check'=>[ app\http\middleware\Auth::class, app\http\middleware\Check::class ], ];
Then, directly use the following method to register the middleware File
Route::rule('hello/:name','hello') ->middleware('check');
Supports the registration of middleware for routing groups
Route::group('hello', function(){ Route::rule('hello/:name','hello'); })->middleware('Auth');
V5.1.8 version starts to support the registration of middleware for a certain domain name
Route::domain('admin', function(){ // 注册域名下的路由规则 })->middleware('Auth');
If you need to pass in additional parameters to the middleware For files, you can use
Route::rule('hello/:name','hello') ->middleware('Auth:admin');
If you use constant definition, you can pass in the middleware parameters in the second parameter.
Route::rule('hello/:name','hello') ->middleware(Auth::class, 'admin');
If you need to define multiple middlewares, use the array method
Route::rule('hello/:name','hello') ->middleware([Auth::class, 'Check']);
You can pass in the same additional parameter
Route::rule('hello/:name','hello') ->middleware([Auth::class, 'Check'], 'admin');
or specify the middleware parameters individually.
Route::rule('hello/:name','hello') ->middleware(['Auth:admin', 'Check:editor']);
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('hello', function(){ Route::rule('hello/:name','hello'); })->middleware(function($request,\Closure $next){ if ($request->param('name') == 'think') { return redirect('index/think'); } 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, 'Check', 'Hello', ];
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, 'admin'], 'Check', 'Hello:thinkphp', ];
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 = ['Auth']; public function index() { return 'index'; } public function hello() { return 'hello'; } }
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 = [ 'Auth' => ['except' => ['hello'] ], 'Hello' => ['only' => ['hello'] ], ]; public function index() { return 'index'; } public function hello() { return 'hello'; } }
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 = 'ThinkPHP'; 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!

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

AI Hentai Generator
Generate AI Hentai for free.

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

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.

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.

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.

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.

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

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