使用PhpManager在Yii2中进行RBAC

时间:2014-11-23 09:47:46

标签: yii2 rbac

如何在没有任何数据库的RBAC中实现Yii 2.0。 我将只有两个角色,即admin and author。 我的RbacController是

<?php
namespace app\commands;

use Yii;
use yii\console\Controller;

class RbacController extends Controller
{
    public function actionInit()
    {
        $auth =  \Yii::$app->authManager;

        // add "createPost" permission
        $createPost = $auth->createPermission('createPost');
        $createPost->description = 'Create a post';
        $auth->add($createPost);

        // add "updatePost" permission
        $updatePost = $auth->createPermission('updatePost');
        $updatePost->description = 'Update post';
        $auth->add($updatePost);

        // add "author" role and give this role the "createPost" permission
        $author = $auth->createRole('author');
        $auth->add($author);
        $auth->addChild($author, $createPost);

        // add "admin" role and give this role the "updatePost" permission
        // as well as the permissions of the "author" role
        $admin = $auth->createRole('admin');
        $auth->add($admin);
        $auth->addChild($admin, $updatePost);
        $auth->addChild($admin, $author);

        // Assign roles to users. 1 and 2 are IDs returned by IdentityInterface::getId()
        // usually implemented in your User model.
        $auth->assign($author, 2);
        $auth->assign($admin, 1);
    }
}

我收到错误

  `PHP Fatal error: Call to a member function createPermission() 
on a non-object in var/www/commands/RbacController.php on line 14
    PHP Fatal Error 'yii\base\ErrorException' with message 'Call to a member
 function createPermission() on a non-object' in /var/www/commands/RbacController.php:14 
执行yii rbac/init

。我正在使用PhpManager的基本模板。我在web.php中添加了'authManager' => [ 'class' => 'yii\rbac\PhpManager', ],。我正在使用基本模板。

3 个答案:

答案 0 :(得分:9)

我知道这有点旧,但我想发布解决方案..至少对我有用。

  

我添加了&#39; authManager&#39; =&GT; [&#39; class&#39; =&GT; &#39; yii \ rbac \ PhpManager&#39;,],   在web.php中

有错误,因为您通过控制台重新运行命令,您需要在console.php的组件部分添加相同的行(与web.php在同一目录中)。

我希望这可以帮助其他有类似问题的人:D

答案 1 :(得分:3)

答案 2 :(得分:0)

在您的控制器中尝试此操作

$auth = new \yii\rbac\PhpManager();
 // add "createPost" permission
$createPost = $auth->createPermission('createPost');
$createPost->description = 'Create a post';
$auth->add($createPost);

http://blog.dedikisme.com/blog/2014/05/09/rpbac-yii2-framework