在 Yii2 中如何使用基本模板为用户分配角色?

How do you assign roles to users with the basic template in Yii2?

http://www.yiiframework.com/doc-2.0/guide-security-authorization.html#role-based-access-control-rbac

在文档中,它说您可以使用以下代码将角色分配给高级模板中的用户:

public function signup()
{
    if ($this->validate()) {
        $user = new User();
        $user->username = $this->username;
        $user->email = $this->email;
        $user->setPassword($this->password);
        $user->generateAuthKey();
        $user->save(false);

        // the following three lines were added:
        $auth = Yii::$app->authManager;
        $authorRole = $auth->getRole('author');
        $auth->assign($authorRole, $user->getId());

        return $user;
    }

    return null;
}

问题是我使用的是基本模板。有没有办法在基本模板中执行此操作?

我考虑过使用afterSave方法;但是,我不确定该怎么做。

public function afterSave($insert)
{

}

知道怎么做吗?

public function afterSave($insert)
{
    $auth = Yii::$app->authManager;
    $authorRole = $auth->getRole('author');
    $auth->assign($authorRole, $this->Id());
}

我认为这可行,但我不完全确定。

它不依赖于使用的模板。

你的例子是正确的,除了少数地方。

$this->Id() 应替换为 $this->id(假设用户 table 的主键名为 id)。

请注意,您还需要调用 afterSave() 方法的父实现并且您错过了 $changedAttributes 参数:

/**
 * @inheritdoc
 */ 
public function afterSave($insert, $changedAttributes)
{
    $auth = Yii::$app->authManager;
    $authorRole = $auth->getRole('author');
    $auth->assign($authorRole, $this->id);

    parent::afterSave($insert, $changedAttributes);
}

为了进一步改进,您可以将保存包装在事务中,因此如果 afterSave() 中的某些内容失败,则不会保存模型(afterSave() 事件处理程序在模型保存到数据库后执行)。

您也可以将分配角色逻辑移动到单独的方法中。

请注意,使用此逻辑,每个注册用户都将拥有该角色。你可以用一些条件包装它,但是最好通过管理界面分配角色。

您可以在 this extension 中看到它是如何实现的。例如,您可以创建单独的表单、操作并使用附加图标扩展 GridView ActionColumn 以分配角色。