简体   繁体   English

Laravel 5 BaseController for middlewear Auth

[英]Laravel 5 BaseController for middlewear Auth

I notice that in the example WelcomeController that requires a user to be logged in has: 我注意到在需要用户登录的示例WelcomeController中有:

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

Should I create a BaseController that extends Controller which contains the above code for all controllers that need the user to be logged in, and extend all my controllers from that? 我应该创建一个扩展Controller的BaseController,它包含需要用户登录的所有控制器的上述代码,并从中扩展我的所有控制器吗?

I wouldn't recommend that. 我不建议这样做。 Instead, consider applying the Middleware to your routes like here: 相反,请考虑将中间件应用到您的路线,如下所示:

Route::group(['middleware' => 'auth'], function()
{
    Route::get('/', function()
    {
        // Has Auth Filter
    });

    Route::get('user/profile', function()
    {
        // Has Auth Filter
    });
});

which is also included the default example on grouped routes in the laravel docs btw. 这也是laravel docs btw中分组路线的默认示例。

EDIT 编辑

Providing another BaseController is possible since it obviously works. 提供另一个BaseController是可能的,因为它显然有效。 But think about more complex situations where middlewares might need to be applied to only some but not all controller methods. 但想想更复杂的情况,其中中间件可能只需要应用于一些但不是所有控制器方法。

Routes offers a whole lot more of flexibility in those cases. 在这些情况下,路由提供了更多的灵活性。

But the most important thing is to stay consistent. 但最重要的是要保持一致。 So just choose what is applicable but prevent your self from mixing it up approaches. 因此,只需选择适用的内容,但防止自己混淆方法。 This way, your app stays maintainable. 这样,您的应用就可以维护。

Another important thing to notice is, that this approach is pretty similar to the Laravel 4 -way of handling this problem ( Route Filters ). 另一个需要注意的重要事项是,这种方法非常类似于处理此问题的Laravel 4路径( 路由过滤器 )。 So if you choose to do it that way, people switching from L4 might have no problems understanding what happens there. 因此,如果您选择以这种方式进行,那么从L4切换的人可能在理解那里发生的事情时没有问题。

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

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