yii2.0Rbac操作

首先在common/config/main-local.php或者main.php里的components下配置

'authManager' => [
 'class' => 'yii\rbac\DbManager',
 'itemTable' => 'auth_item',
 'assignmentTable' => 'auth_assignment',
 'itemChildTable' => 'auth_item_child',
  ],

打开cmd命令

进入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控制器进行测试




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值