Yii2 RBAC DbManager错误在null时调用成员函数getRole()


Yii2 RBAC DbManager error Call to a member function getRole() on null

我已经通过实现SQL代码来设置表和rbac/init脚本来填充角色/权限,从而设置了数据库等。

我在用户创建时有一个assign(),但我一直在getRole()上收到这个错误:

yii''base''ErrorException在null上调用成员函数getRole()

   public function addUser()
{
    if($this->validate()) {
        $user = new User();
        $auth_key = Yii::$app->getSecurity()->generateRandomString(32);
        $this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password);
        $user->email = $this->email;
        $user->password = $this->password;
        $user->active = $this->active;
        $user->firstname = $this->firstname;
        $user->lastname = $this->lastname;
        // $user->nickname = $this->nickname;
        $user->datecreated = time();
        $user->auth_key = $auth_key;
        $user->save(false);
        $auth = Yii::$app->authManager;
        $authorRole = $auth->getRole($this->role);
        $auth->assign($authorRole, $user->getId());
        return $user;
    }else{
        return false;
    }
}

$role变量与其他用户属性一起通过$_POST传递。

请帮忙。谢谢

你做得不对。

这里的问题似乎是Yii::$app->authManager没有在应该设置的时候设置。这可能意味着你的main.php配置文件没有包含正确的信息。它应该包含以下组件:

return [
    // ...
    'components' => [
        'authManager' => [
            'class' => 'yii'rbac'DbManager',
        ],
        // ...
    ],
];

(http://www.yiiframework.com/doc-2.0/guide-security-authorization.html#configuring-rbac经理)

在上面链接的示例中,使用了PhpManager,但在您的情况下,您将希望使用yii''rbac''DbManager

这样做意味着您将只有一个加载的管理器,并且还将解锁所有操作筛选选项。

我似乎已经通过替换解决了这个问题

$auth = Yii::$app->authManager;

带有

$auth = new DbManager;

如果这是错误的做法,请告诉我!