php - Laravel Controller 中每个方法的 Action 过滤器

标签 php laravel

我正在为客户构建一个相当广泛的应用程序,我将不得不生成某种组权限控制。我决定使用 Cartalyst 及其 Sentry 软件包。
到目前为止一切顺利!

现在我遇到的问题是,检测用户组权限的最佳方法是什么,因为不止一个,所以我不能只使用一个过滤器就完事了。

例如,我会做这样的事情:

对于需要管理员级别访问权限的页面

Route::group(array('before' => 'is_admin'), function()
{
       Route::get('admin', array('as'=>'admin', 'uses'=>'admin@index'));
       // Other methods that require admin-level access
});

对于需要更多级别访问权限的页面等..

Route::group(array('before' => 'is_moderator'), function()

    {
           Route::get('orodja/plosca', array('as'=>'moderator', 'uses'=>'moderator@index'));
           // Other methods that require moderator-level access
    });

我在使用这种方法时遇到的问题是,我需要为每个 Controller 操作定义一个新路由,这对我来说真的不是最佳实践。

接下来我考虑使用 Controller::detect() 注册所有 Controller 并使它们成为 REST-full 但我这里的问题是,我只能将过滤器应用于 Controller 的构造方法而不是一个 Action 。如果我在一个 Controller 中有不同访问级别的方法怎么办?

所以我的问题是:解决这个问题的最佳方法是什么?有什么方法可以将 Action 过滤器应用于单个 Controller 方法,而不是 Controller 构造函数。 p>

谢谢,对不起我的英语!

最佳答案

您可以将过滤器附加到以给定 URI 开头的所有请求(请参阅 official doc on filters)

Route::filter('pattern: admin/*', 'auth');

或者您可以仅将过滤器附加到 Controller 中的某些操作:

$this->filter('before', 'auth')->only(array('index', 'list'));

附带说明一下,您不必为您拥有的每个 Controller 操作创建路由。如果您使用 Route::controller('admin::home'); 注册您的 Controller ,它将自动触发。

另一种选择是您只为所有角色定义一个auth 过滤器,然后检查过滤器中的不同角色。

关于php - Laravel Controller 中每个方法的 Action 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15423676/

相关文章:

php - 如何将 Eloquent 'saveMany' 与数据透视表一起使用?

php - RegEx - 获取未包装的元素数

javascript - 取消选中通过 POST[] 的 Echo 检查的复选框

php - 此集合实例上不存在 Laravel 属性

php - 在 Nginx 上模拟 Apache 目录别名

php - 在 laravel 的数据库中播种时出错

php - 在用php上传文件时需要输入标签而不是浏览按钮

php - Yii2 ActiveRecord 与关系结果转换为 JSON

javascript - php $_POST 返回空数组

php - Laravel 与数据透视表关系中的错误