2014-11-23 66 views
4

如何在沒有任何數據庫的情況下在Yii 2.0中實現RBAC。我將只有2個角色,即admin and author。 我RbacController是Yii2中的RBAC與PhpManager

<?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); 
    } 
} 

在執行yii rbac/init我得到一個錯誤

`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 

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

回答

8

我知道這是有點老了,但我要發佈的解決方案。至少是什麼對我有用。

我已經添加 'authManager'=> [ '類'=> 'YII \ RBAC \ PhpManager'],在 web.php

有錯誤,因爲你重新通過控制檯運行命令,您需要在console.php的組件部分(與web.php位於同一目錄中)添加同一行。

我希望這可以幫助其他人誰也有類似的問題:d

+0

感謝。這解決了我的問題。 – Qinjie 2015-04-12 11:35:41

+0

或將其添加到常用配置main.php,以便它可供所有應用程序使用。 – Barry 2016-10-07 09:22:54