Yii2RBAC uses DbManager to determine backend permissions _ php instance

Source: Internet
Author: User
This article mainly introduces how yii2RBAC uses DbManager to judge the background permissions, and analyzes in detail the principle and related skills of Yii2 permission control based on the instance form, you can refer to the following example to describe how yii2 RBAC uses DbManager to determine backend permissions. We will share this with you for your reference. The details are as follows:

Generate a table in the yii2 framework according to the document

Yii migrate -- migrationPath = @ yii/rbac/migrations/

Generate the following four tables:

Auth_assignment
Auth_item_child
Auth_item
Auth_rule

Use the gii of yii to quickly generate the corresponding model. However, because the auth_item table stores the role and permission at the same time, we need to divide the role and permission for the curd operation, therefore, I have created two models, RoleForm and PermissionForm, to separate roles and permissions. Because the role is closely linked to the permission, an attribute $ child is added to the model generated by auth_item, which will be used later.

The code for role model is as follows:

<? Phpnamespace app \ models; use Yii; use app \ models \ AuthItem; use yii \ rbac \ Item; /** role model * artist at the fingertip */class RoleForm extends AuthItem {public function init () {parent: init (); $ this-> type = Item :: TYPE_ROLE; // yii-rbac-Role hides the inherited constant. The value here is 1 }}

The code for permission model is as follows:

<? Phpnamespace app \ models; use Yii; use app \ models \ AuthItem; use yii \ rbac \ Item; /** permission model * artist at the fingertip */class PermissionForm extends AuthItem {public function init () {parent: init (); $ this-> type = Item :: TYPE_PERMISSION; // constant value 2 }}

Add an attribute to the AuthItem model.

<? Phpclass AuthItem ...... public $ child; // used to add role permissions ......

Now we have the corresponding controller.

First, we should say that the permission controller needs to use the extension provided by the system when writing the controller.
...
Use yii \ rbac \ Permission;
...

/** Add permissions */public function actionCreate () {$ model = new PermissionForm (); if ($ model-> load (Yii :: $ app-> request-> post () & $ model-> validate () {// permission object in rbac $ permission = new Permission (); $ permission-> name = trim ($ model-> name); $ permission-> type = $ model-> type; // permission to add Yii :: $ app-> authManager-> add ($ permission );}}

When the modification is made, the other method is changed.

/** Param string $ name: the modified permission name * param Object $ permission is the same as adding the submitted data */Yii: $ app-> authManager-> update ($ name, $ permission );

Here is delete

//Returns the named permission.$permission = Yii::$app->authManager->getPermission( $name );//Removes a permission or rule from the RBAC system.Yii::$app->authManager->remove( $permission );

The cud of the permission is done, and you will not write it after checking it.

The following figure shows the role controller.

Carry this

Use yii \ rbac \ Role;/** Add Role */public function actionCreate () {$ model = new RoleForm (); if ($ model-> load (Yii :: $ app-> request-> post () & $ model-> validate () {// instantiate the role object $ Role = new role (); $ role-> name = $ model-> name; $ role-> type = $ model-> type; // add a role Yii :: $ app-> authManager-> add ($ role);} // permission list (when adding a role, we can see whether there are permissions to add) $ permissions = $ this-> loadPermission (); // Set $ model to $ permissions .... render to view}

/** Modify * param string $ name the modified role name * param Object $ role and add the same data submitted */$ bool = Yii :: $ app-> authManager-> update ($ name, $ role );

Deleting a file is troublesome.

/** Param string $ name role name */$ role = Yii ::$ app-> authManager-> getRole ($ name ); // Obtain the current role object // Returns the child roles. $ childAll = Yii: $ app-> authManager-> getChildren ($ role); if (isset ($ childAll )) {// delete the permission foreach ($ childAll as $ value) {// Returns the named permission. $ perObj = Yii: $ app-> authManager-> getPermission ($ value); // Removes a child from its parent. yii: $ app-> authManager-> removeChild ($ role, $ perObj) ;}} Yii: $ app-> authManager-> remove ($ role ); // delete the role.

The most important thing is to grant permissions to the role, right?

// The permissions of the current role $ childArray = $ this-> loadRolePermission ($ model-> name); // this is the returned permission array if (! Empty ($ childArray) {$ model-> child = $ childArray;} else {$ model-> child = array ();} // Returns all permissions in the system. $ permissions = Yii: $ app-> authManager-> getPermissions (); $ perArr = array (); foreach ($ permissions as $ key => $ value) {$ perArr [$ value-> name] = $ value-> name;} if ($ model-> load (Yii: $ app-> request-> post ()) & $ model-> validate () {// role object $ child = isset ($ _ POST ['authitem'] ['Chi Ld '])? $ _ POST ['authitem'] ['child ']: NULL; // The form cannot verify the child. Therefore, when it is NULL, it jumps back to the original page if (empty ($ child )) {return $ this-> redirect (.. page to jump ..);} // determine whether a role has been assigned permissions. if the role has been assigned permissions, delete the role. otherwise, add a new if (! Empty ($ childArray) {// Removed all children form their parent. $ bool = Yii: $ app-> authManager-> removeChildren ($ model); if (! $ Bool) {throw new HttpException (404, 'Don't confuse me! Share your face ~~~ ') ;}} // Current role object $ role = Yii: $ app-> authManager-> getRole ($ model-> name ); // add if (isset ($ child) {foreach ($ child as $ val) for the child permission {// get the permission $ childObj = Yii :: $ app-> authManager-> getPermission ($ val); // write data to the item_child table (permission table) Yii ::$ app-> authManager-> addChild ($ role, $ childObj);} return $ this-> redirect (.. page to jump ..);}}

Finally, the role is associated with the user.

/** Key part of the code used to create a role-to-user Association * // Returns the named role. $ role = Yii: $ app-> authManager-> getRole ($ roleName); // Assigns a role to a user. yii: $ app-> authManager-> assign ($ role, $ userId );
/** Permission detection * param int | string $ userId user id * param string $ permission name */Yii: $ app-> authManager-> checkAccess ($ userId, $ permission ))

The following is the permission judgment

/** Permission detection * param int | string $ userId user id * param string $ permission name */Yii: $ app-> authManager-> checkAccess ($ userId, $ permission ))

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.