【发布时间】:2016-06-09 09:14:24
【问题描述】:
我看过很多 Yii 2 RBAC 教程,但我不能真正理解如何实现这些规则。在 Yii 2 指南中,他们介绍了规则是如何制定的,但并未真正介绍如何在控制器的行为或其他地方实现它。关于这件事,我真的需要一些启示。
我现在拥有的是一个文档上传系统,其中我有两个角色,即管理员和编码器。基本上,管理员角色可以做所有事情,而编码器角色只能创建、查看-拥有、更新-拥有和删除-拥有。我已经创建了一个名为 encodedBy 的规则。
这是我的 EncoderRule 中的代码
namespace app\rbac; use yii\rbac\Rule;
/** * Checks if encoded_by matches user passed via params */ class EncoderRule extends Rule {
public $name = 'encodedBy';
/**
* @param string|integer $user the user ID.
* @param Item $item the role or permission that this rule is associated with
* @param array $params parameters passed to ManagerInterface::checkAccess().
* @return boolean a value indicating whether the rule permits the role or permission it is associated with.
*/
public function execute($user, $item, $params)
{
return isset($params['document']) ? $params['document']->encoded_by == $user : false;
} }
我将数据存储在“文档”表中,其中有一个名为“encoded_by”的字段。
【问题讨论】:
-
这个视频很好地解释了 RBAC 的工作原理:youtube.com/watch?v=vLb8YATO-HU