問題描述
Laravel 5 文檔 描述了兩種分配中間件的方法:
- 將中間件分配給控制器的路由.
- 在控制器的構造函數中指定中間件.
然而,我意識到在控制器__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.
這篇關于如何設置 Laravel 中間件的執行順序?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!