【问题标题】:Laravel/PHP - returning/redirecting from child classLaravel/PHP - 从子类返回/重定向
【发布时间】:2014-11-18 19:07:44
【问题描述】:

这是我的子控制器:

class VolunteersController extends \BaseController
{
    public function index()
    {
        $this->checkForRoles(['admin']);
        //list some secret stuff for admin
    }
}

在我的基本控制器中,我这样做了:

class BaseController extends Controller
{
    protected function checkForRoles($roles)
    {
        foreach ($roles as $role) {
            if (!(Auth::user()->hasRole($role))) {
                return Redirect::to('/');
            }
        }
    }
}

现在我期望的是,如果他的角色不是管理员,BaseController 中的 return Redirect::to('/'); 行会将用户重定向到主页。

但这并没有发生。 //list some secret stuff for admin 无论如何都会被执行。

编辑: 有些人可能想知道,为什么我不使用过滤器。是的,所需的功能是过滤器,但显然过滤器不支持 Laravel 中的数组参数。如您所见,我需要将一组角色传递给函数。

请帮忙。

【问题讨论】:

  • return Redirect::to('/');这一行中删除return,并且可以在Redirect::to('/');之后使用exit;如果这可以解决问题,我会给出答案。
  • 我也猜到了。它不起作用。
  • 猜到了还是你试过了? :)
  • 我说“这行不通。”这意味着我试过了。 :)
  • 为什么不把它放在前置过滤器中?

标签: php laravel laravel-4 laravel-routing


【解决方案1】:

我会将逻辑移至过滤器,这将允许Redirect 正常运行。这就是过滤器的设计目的。

如果你需要向过滤器传递多个角色,而不是向过滤器传递一个数组(Laravel 不允许这样做),使用像“+”这样的分隔符,然后 explode 过滤器中的参数来模拟传递一个数组。

例如,您的路线是:

Route::get('volunteer', array(
    'before' => 'roles:admin+author', 
    'uses' => 'VolunteersController@index'
));

...然后您的过滤器可以轻松地将多个角色转换为数组:

Route::filter('roles', function($route, $request, $roles)
{
    $roles = explode('+', $roles);
    // 'admin+author' becomes ['admin', 'author'];
    // continue with your checkForRoles function from above:
    foreach ($roles as $role) {
        if (!(Auth::user()->hasRole($role))) {
            return Redirect::to('/');
        }
    }
}

然后你可以从 BaseController 中移除逻辑。

或者,您可以将多个参数作为逗号分隔列表传递给过滤器。因此,如果您使用'before' => 'roles:admin,author' 调用您的路线,您可以使用func_get_args() 在您的过滤器中访问它们:

Route::filter('roles', function($route, $request, $roles)
{
    $roles = array_slice(func_get_args(), 2); // remove $route and $request
    //...continue as above.

【讨论】:

  • $roles = array_slice(func_get_args(), 2);
  • @Andreas:当然,这更简单。我更新了答案。谢谢!
【解决方案2】:

仅当 VolunteersController::index() 将返回“重定向”时才会发生重定向。它在您的代码中没有这样做。

如果你有,它会的

class VolunteersController extends \BaseController
{
    public function index()
    {
        if ($res = $this->checkForRoles(['admin'])) return $res;
        //list some secret stuff for admin
    }
}

【讨论】:

  • 是的。但我想避免在我的父控制器中使用 if 语句。有没有其他办法?
  • 如果你想使用 Laravel 的重定向机制,不要这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-09
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
相关资源
最近更新 更多