首先在common/config/main-local.php或者main.php里的components下配置
'authManager' => [
'class' => 'yii\rbac\DbManager',
'itemTable' => 'auth_item',
'assignmentTable' => 'auth_assignment',
'itemChildTable' => 'auth_item_child',
],
进入phpstudy\www\advanced
yii migrate(运行这个命令,生成user表)
yii migrate --migrationPath=@yii/rbac/migrations/ 运行此命令生成权限数据表 在下图
在后台根目录下创建rbac目录
创建RbacController控制器
<?php /** * Created by PhpStorm. * User: 郭子健 * Date: 2017/11/15 * Time: 14:06 */ namespace backend\controllers; use Yii; use yii\web\Controller; class RbacController extends Controller { public function actionAuth() { $auth = \Yii::$app->authManager; // 删除全部 $auth->removeAll(); // 增加权限 $postAdd = $auth->createPermission('Add'); $postAdd->description = '文章添加'; $auth->add($postAdd); $postDelete = $auth->createPermission('Delete'); $postDelete->description = '文章删除'; $auth->add($postDelete); $postUpdate = $auth->createPermission('Update'); $postUpdate->description = '文章编辑'; $auth->add($postUpdate); $postSelect = $auth->createPermission('Select'); $postSelect->description = '文章查看'; $auth->add($postSelect); // 增加角色 $author = $auth->createRole('超级'); $auth->add($author); $reader = $auth->createRole('中级'); $auth->add($reader); $editor = $auth->createRole('低级'); $auth->add($editor); // 为角色赋予权限 $auth->addChild($author, $postAdd);// 作者 添加文章 $auth->addChild($author, $postUpdate);// 作者 编辑文章 $auth->addChild($reader, $postSelect);// 读者 看文章 $auth->addChild($editor, $postDelete); $auth->addChild($editor, $postSelect); $auth->addChild($editor, $author); $auth->addChild($editor, $reader); // 为用户分配角色 $auth->assign($author, 1); $auth->assign($reader, 2); } }
然后在postController控制器进行测试