1, first we want to configure RBAC in the component, as follows (common/config/main-local.php or main.php).
' AuthManager ' = [' class ' = ' Yii\rbac\dbmanager ', ' itemTable ' = ' auth_item ', ' assignmenttable ' and ' auth_ ' Assignment ', ' itemchildtable ' = ' auth_item_child ',], of course, in the configuration can also set the default role, but I did not write. RBAC supports two kinds, phpmanager and DbManager, where I use DbManager.
yii Migrate [email protected]/rbac/migrations/Run this command to generate a permission data table
2, configuration is complete, below we try to create a license permiassion, the code is as follows
Public Function CreatePermission ($item) {$auth = Yii:: $app->authmanager;
$createPost = $auth->createpermission ($item); $createPost->description = ' created '. $item. ' Permit '; $auth->add ($createPost); }
3. Ok, let's do it, let's create a character. Roles
Public Function Createrole ($item) {$auth = Yii:: $app->authmanager;
$role = $auth->createrole ($item); $role->description = ' created '. $item. ' Role '; $auth->add ($role); }
4, good, is so simple, do not be excited, the following is more simple, to assign a role to the license, on the Code
static public Function createempowerment ($items) {$auth = Yii:: $app->authmanager;
$parent = $auth->createrole ($items [' name ']); $child = $auth->createpermission ($items [' description ']);
$auth->addchild ($parent, $child); }
5, good, the allocation of the license is also created, I do, Tainima simple, continue on the code, assign users to the role
static public Function assign ($item) {$auth = Yii:: $app->authmanager; $reader = $auth->createrole ($item [' name ']); $auth->assign ($reader, $item [' description ']); }
6, good good, it is so simple, I can not believe the mother, you believe it??? The final step is to verify that the user has permissions
Public Function Beforeaction ($action) {$action = Yii:: $app->controller->action->id; if (\yii:: $app->user->can ($action)) {return true; }else{throw new \yii\web\unauthorizedhttpexception (' Sorry, you have not been granted permission to do so now '); } }
Well, it's all over with a damn breath. Of course, can be created to be able to modify and delete, modify and delete are multi-table association operations, Yii also for me to write the method, of course, you can also write yourself, is a little something.
Database SQL file Address/vendor/yiisoft/yii2/rbac
From: http://blog.sina.com.cn/s/blog_88a65c1b0101izml.html
The following describes a yii2.0 Rbac permission settings, gossip less, directly on the code,