Home>Article>PHP Framework> What is the usage of thinkphp middleware?

What is the usage of thinkphp middleware?

WBOY
WBOY Original
2022-02-24 16:26:51 2920browse

In thinkphp, the class files created in the "APP\middleware" directory are middleware, which are mainly used to intercept or filter HTTP requests of applications and perform necessary business processing. They can be divided into global middleware , routing middleware and controller middleware.

What is the usage of thinkphp middleware?

The operating environment of this article: Windows 10 system, ThinkPHP version 5, Dell G3 computer.

What is the usage of thinkphp middleware

1. Middleware file definition

Create in the APP\middleware directory The class files are all middleware. Global middleware, routing middleware, and controller middleware can all be referenced through directory paths. Multiple applications should create a new middleware directory in their own application directory, and then create class files below.

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 middleware under the application/http/middleware directory.

2. Middleware file reference or use

After creating the middleware file in one step

(1) Use

as a global middleware. In the middleware.php file in the APP directory, add the path and file in 1, such as \app\middleware\chushimima::class, this is as Use global middleware. It works globally.

Middleware that is not registered in middleware.php is not global middleware. It is divided into routing middleware and controller middleware according to different definition methods.

(2) Use as routing middleware

Still the same middleware class file \app\middleware\chushimima, the route in the route directory under the APP directory In the definition file, add routing rules, such as

Route::rule('index/denglu','index/denglu'); ->middleware('\app\middleware\chushimima');

. This is the routing middleware, which only works when accessing this route.

(3) Use as controller middleware

Still the same middleware class file \app\middleware\chushimima, add the following to your controller file Code, such as

class Index extends baseController { protected $middleware='\app\middleware\chushimima';

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What is the usage of thinkphp middleware?. 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