Yii2 Rbac method of using Dbmanager to realize background permission judgment _php instance

Source: Internet
Author: User
Tags smarty template yii

This article illustrates the method of Yii2 RBAC using Dbmanager to realize background authority judgment. Share to everyone for your reference, specific as follows:

To first generate a table in the YII2 framework based on the document

Yii Migrate--migrationpath= @yii/rbac/migrations/

The following 4 tables are generated:

Auth_assignment
Auth_item_child
Auth_item
Auth_rule

Use Yii's gii to quickly generate the corresponding model, but because Auth_item tables store roles and permissions at the same time, because we want to do curd operations with roles and permissions later, So I've created a new roleform and permissionform two model to differentiate between roles and permissions. Because the role and permissions are tightly linked, and in the Auth_item generated model to add a property $child, the following will be used in the first time.

Here's the code for role model.

<?php
namespace App\models;
Use Yii;
Use App\models\authitem;
Use Yii\rbac\item;
 * * * Role model
 * Artist on the
 fingertips
/class Roleform extends Authitem
{public
  function init () {
    Parent::init ();
    $this->type = Item::type_role;//yii-rbac-role Hide inheritance constant The value here is 1
  }
}

The following are the relevant code for the permission model

<?php
namespace App\models;
Use Yii;
Use App\models\authitem;
Use Yii\rbac\item;
*
 * Permission Model
 * The artist on the
 fingertips
/class Permissionform extends Authitem
{public
  function init () { C12/>parent::init ();
    $this->type = item::type_permission;//constant value 2
  }
}

Additionally, add an attribute to the Authitem model

<?php
class Authitem
..... public $child;//For role permission add ...


Now it's up to our corresponding controller.

First of all, we say that the permission controller to write the controller to use the system's own extension
。。。
Use yii\rbac\permission;
。。。


 * * Permissions Add/* Public
function actioncreate () {
  $model = new Permissionform ();
  if ($model->load (Yii:: $app->request->post ()) && $model->validate ()) {
    //rbac permission object
    $permission = new permission ();
    $permission->name = Trim ($model->name);
    $permission->type = $model->type;
    Permissions add
    Yii:: $app->authmanager->add ($permission);
  }


The other change is the same way.

*
 * param string $name modified permission name
 * param Object $permission data submitted as added
/Yii:: $app-> Authmanager->update ($name, $permission);

Here is the 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 rights are all done, the view is not written

Here is the role controller

Take this.

Use Yii\rbac\role;
 * * Role Add */public
function actioncreate () {
  $model = new Roleform ();
  if ($model->load (Yii:: $app->request->post ()) && $model->validate ()) {
      //Instantiate role object
      $role = New role ();
      $role->name = $model->name;
      $role->type = $model->type;
      Add role
      Yii:: $app->authmanager->add ($role);
  }
  Permission list (when adding a role we can see whether there is currently permission to add)
  $permissions = $this->loadpermission ();
  Will $model with $permissions .... Render to view just fine.


*
 * Modify
 * param string $name modified role name
 * param Object $role data submitted with the same as add *
 *
$bool = Yii:: $app->a Uthmanager->update ($name, $role);

It's a bit of a hassle when you delete it.


 * * param string $name role name
/$role = Yii:: $app->authmanager->getrole ($name);//Get current Role object
// Returns the child roles.
$childAll = Yii:: $app->authmanager->getchildren ($role);
if (Isset ($CHILDALL)) {//delete permission
  foreach ($childAll as $value) {
    //returns the named permission.
    $PEROBJ = Yii:: $app->authmanager->getpermission ($value);
    Removes a child in its parent.
    Yii:: $app->authmanager->removechild ($role, $PEROBJ);
  }
Yii:: $app->authmanager->remove ($role);//finally delete our character.

The most important thing is that we have to give the character permission, right, the following code

The permissions that the current role has $childArray = $this->loadrolepermission ($model->name);//This is the return 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 '] [' child ']) ?
  $_post[' Authitem ' [' Child ']: NULL; The form cannot validate the child so when empty, skip back to the original page if (empty ($child)) {return $this->redirect (...
  You want to jump the page ...);
    ///Determine whether the role is assigned permissions, is deleted, and vice versa 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 try to fool me!
    Gather your face ~ ~ ~); }//Current role Object $role = Yii:: $app->aUthmanager->getrole ($model->name); Child permissions Add if (Isset ($child)) {foreach ($child as $val) {//get permission $CHILDOBJ = Yii:: $app->authman
      Ager->getpermission ($val);
    Write data to a Item_child table (permission table) Yii:: $app->authmanager->addchild ($role, $CHILDOBJ); return $this->redirect (...
  You want to jump the page ...);

 }
}

And finally, our last controller. Role associated with user


 * * Create a key part of the code associated with the user/
 //returns the named role
.
$role =yii:: $app->authmanager->getrole ($roleName);
Assigns a to a user.
Yii:: $app->authmanager->assign ($role, $userId); <pre name= "code" class= "PHP" >/*
 * Permission detection
 * param Int| String $userId User ID
 * param string $permission permission name *
 *
Yii:: $app->authmanager->checkaccess ($ UserId, $permission))

Here is the right to judge

*
 * Permission detection
 * param int| string $userId user ID
 * param string $permission permission name * *
Yii:: $app-> Authmanager->checkaccess ($userId, $permission))

For more information on YII-related content, readers who are interested in this site can view the topics: Introduction to YII Framework and summary of common skills, "Summary of PHP Excellent development framework", "Smarty Template Introductory Course", "Introduction to PHP object-oriented programming", "PHP string" Summary of Usage , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"

I hope this article will help you with the PHP program design based on the YII framework.

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.