如何设置 Laravel 中间件的执行顺序?

2021-12-18 00:00:00 php laravel laravel-5 laravel-middleware

Laravel 5 文档 描述了两种分配中间件的方法:

  1. 将中间件分配给控制器的路由.
  2. 在控制器的构造函数中指定中间件.

然而,我意识到在控制器__construct() 函数中编写的任何代码都会在中间件之前运行,即使中间件是在控制器的 __construct 函数的第一行声明.

However, I realised that any code written in the controllers __construct() function will run before the Middleware, even if the Middleware is declared on the first line of the controller's __construct function.

我在 Laravel github 存储库中找到了一个关于类似问题的错误报告.然而,一位合作者结束了这个问题,指出这是预期的行为.".

I found a bug report for a similar issue in the Laravel github repository. However a collaborator closed the issue stating "This is the expected behaviour.".

我认为 middleware 应该是应用程序之外的层",而 __construct 函数是应用程序的一部分.

I am thinking that middleware should be "layers" outside the application, while the __construct function is part of the application.

为什么 __construct 函数在中间件之前执行(假设它是在中间件运行之前声明的)?为什么这是预期的?

Why is the __construct function executed before the middleware (given it is declared before middleware runs)? and why this is expected?

推荐答案

应用程序逻辑驻留在控制器的方法中.所以基本上应用程序存在于控制器的方法中,而不是整个控制器本身.

The application logic resides in the controller's methods. So basically application lives in the controller's methods, not in the whole controller itself.

中间件在请求进入相应的控制器方法之前运行.因此,这始终在实际应用程序之外.除非所有中间件都通过请求,否则不会执行任何控制器方法.

Middleware runs BEFORE the request enters the respective controller method. And thus, this is always OUTSIDE the real application. No controller method is executed unless all the Middlewares are passing the request.

您放入控制器构造函数中的 $this->middleware("MyMiddleware"); 语句,注册 MyMiddleware 以在执行之前进行检查请求进入应用程序.

The $this->middleware("MyMiddleware"); statements that you put in the controller constructor, REGISTERS the MyMiddleware for checking before the request enters the application.

如果你看到一个中间件的代码并且如果请求通过,则我们使用 $next($request); 语句将其发送到下一个中​​间件.这允许为单个请求执行多个中间件.现在,如果 Laravel 直接在 $this->middleware(...); 语句处运行中间件,Laravel 可能无法知道接下来应该检查哪个中间件.

If you see the code of a middleware and if the request is passing, then we send it to the next middleware using the $next($request); statement. This allows multiple middlewares to be executed for a single request. Now, if Laravel run the middleware right at the $this->middleware(...); statement, Laravel would probably not be able to know which middleware should be next checked.

所以,Laravel 通过先注册所有中间件,然后将请求一个一个地传递给所有中间件来解决这个问题.

So, Laravel solves this by registering all the middlewares first, then passing the request through all the middlewares one by one.

相关文章