如何设置Laravel中间件的执行顺序? [英] How to set the Laravel middleware order of execution?

查看:584
本文介绍了如何设置Laravel中间件的执行顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是,我意识到,即使 Middleware 已在 Middleware 中声明,控制器__construct()函数中编写的任何代码都将在 Middleware 之前运行.控制器的__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("My\Middleware");语句,在请求进入应用程序之前注册My\Middleware以进行检查.

The $this->middleware("My\Middleware"); statements that you put in the controller constructor, REGISTERS the My\Middleware 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.

这篇关于如何设置Laravel中间件的执行顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆