繁体   English   中英

路由中的中间件和控制器构造函数中的中间件有什么区别?

[英]What is difference between middleware in routes and middleware in controller's constructor?

我对 Laravel 很陌生,想深入了解中间件。 我想知道在路由中附加中间件或在控制器的构造函数中添加中间件之间的主要区别是什么。
例如它是名为UserController的控制器的构造函数

public function __construct() {
  $this->middleware('age');
}

让我们假设它是同一个控制器的路由,即UserController

Route::get('user/profile', function () {
    //
})->middleware('age');

我的主要问题是,我应该在路由和控制器的构造函数中添加中间件,还是只在其中之一中添加中间件?

两者都将执行相同的任务,只是您可以用两种不同的方式编写。

However, it is more convenient to specify middleware within your controller's constructor. Using the middleware method from your controller's constructor, you may easily assign middleware to the controller's action. You may even restrict the middleware to only certain methods on the controller class.

https://laracasts.com/discuss/channels/laravel/middleware-in-controller-or-on-route

如果控制器中有条件,则取决于您的情况,您必须使用第一种情况,否则最好使用第二种情况。

public function __construct() {
  $this->middleware('age');
}
```````````````````````````````````````````````````````````````````````````````
Global middlewares are those that will be running during every HTTP request of your application. In the $middleware property of your app/Http/Kernel.php class, you can list all the global middleware for your project.

```````````````````````````````````````````````````````````````````````
Route::get('user/profile', function () {
    //
})->middleware('age');
````````````````````````````````````````````````````````````````````````
When you want middlewares to specific routes, you have to add the middleware with a key for your app/Http/Kernel.php file and such middlewares are called route middleware. $routeMiddleware by default holds entries for the middleware that are already incorporated in Laravel. For adding your custom middleware, you need to append them to the list and add a key of your choice

[link]https://www.w3schools.in/laravel-tutorial/middleware/  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM