


yii2 RBAC uses DbManager to implement background permission judgment_php example
The example in this article describes how yii2 RBAC uses DbManager to implement background permission judgment. Share it with everyone for your reference, the details are as follows:
First generate the table in the yii2 framework based on the document
yii migrate --migrationPath=@yii/rbac/migrations/
Generate the following 4 tables:
auth_assignment
auth_item_child
auth_item
auth_rule
Use yii's gii to quickly generate the corresponding model, but since the auth_item table stores roles and permissions at the same time, since we need to divide roles and permissions later to perform curd operations, I created two new models here, RoleForm and PermissionForm, to distinguish the roles. with permissions. Since roles are closely connected with permissions, an additional attribute $child is added to the model generated by auth_item, which will be used later and is ignored for now.
The following is the relevant code of the character model
<?php namespace app\models; use Yii; use app\models\AuthItem; use yii\rbac\Item; /* * 角色model * 指尖上的艺术家 */ class RoleForm extends AuthItem { public function init() { parent::init(); $this->type = Item::TYPE_ROLE;//yii-rbac-Role隐藏继承常量这里的值是1 } }
The following is the relevant code of the permission model
<?php namespace app\models; use Yii; use app\models\AuthItem; use yii\rbac\Item; /* * 权限model * 指尖上的艺术家 */ class PermissionForm extends AuthItem { public function init() { parent::init(); $this->type = Item::TYPE_PERMISSION;//常量值 2 } }
In addition, add an attribute to the AuthItem model
<?php class AuthItem..... public $child;//用于角色权限添加 ......
Now comes our corresponding controller
First of all, let’s talk about the permission controller. When writing a controller, we need to use the extensions that come with the system
. . .
use yiirbacPermission;
. . .
/* * 权限添加 */ public function actionCreate() { $model = new PermissionForm(); if( $model->load( Yii::$app->request->post() ) && $model->validate() ) { //rbac中permission对象 $permission = new Permission(); $permission->name = trim( $model->name ); $permission->type = $model->type; //权限添加 Yii::$app->authManager->add( $permission ); } }
When modifying, everything else remains the same, just change the method
/* * param string $name 修改的权限名 * param Object $permission 跟添加一样提交上来的数据 */ 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 permissions is all done, so I won’t write it after checking it
The following is the character controller
Bring this
use yii\rbac\Role; /* * 角色添加 */ public function actionCreate() { $model = new RoleForm(); if ( $model->load( Yii::$app->request->post() ) && $model->validate() ) { //实例化角色对象 $role = new Role(); $role->name = $model->name; $role->type = $model->type; //添加角色 Yii::$app->authManager->add( $role ); } //权限列表( 添加角色的时候我们就可看到当前有没有权限来添加 ) $permissions = $this->loadPermission(); //将$model跟$permissions....渲染到视图就好了 }
/* * 修改 * param string $name 修改的角色名 * param Object $role 跟添加一样提交上来的数据 */ $bool = Yii::$app->authManager->update( $name, $role );
It’s more troublesome when deleting it
/* * param string $name 角色名 */ $role = Yii::$app->authManager->getRole( $name );//获取当前角色对象 //Returns the child roles. $childAll = Yii::$app->authManager->getChildren( $role ); if ( isset($childAll) ) {//逐一删除权限 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 );//最后删除我们的角色了
The most important thing is that we need to give permissions to the role, right? The code is as follows
//当前角色所拥有的权限 $childArray = $this->loadRolePermission( $model->name );//这个就是返回权限数组 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() ) { //角色对象 $child = isset( $_POST['AuthItem']['child'] ) ? $_POST['AuthItem']['child'] : NULL; //表单无法验证child所以当为空的时候跳回原页面 if ( empty( $child ) ) { return $this->redirect(..你们要跳的页面..); } //判断角色是否分配权限,已分配则删除,反之增加新的 if ( !empty( $childArray ) ) { //Removed all children form their parent. $bool = Yii::$app->authManager->removeChildren( $model ); if ( !$bool ) { throw new HttpException(404, '别想糊弄我!凑你一脸~~~'); } } //当前角色对象 $role = Yii::$app->authManager->getRole( $model->name ); //child权限添加 if( isset( $child ) ) { foreach ( $child as $val) { //获取权限 $childObj = Yii::$app->authManager->getPermission($val); //给item_child表写入数据(权限表) Yii::$app->authManager->addChild( $role, $childObj ); } return $this->redirect(..你们要跳的页面..); } }
Finally, our last controller is the role associated with the user
/* * 创建角色跟用户之间关联的关键部分代码 */ //Returns the named role. $role =Yii::$app->authManager->getRole( $roleName ); // Assigns a role to a user. Yii::$app->authManager->assign( $role, $userId );<pre name="code" class="php">/* * 权限检测 * param int| string $userId 用户id * param string $permission 权限名 */ Yii::$app->authManager->checkAccess( $userId , $permission ) )
The following is to determine the permissions
/* * 权限检测 * param int| string $userId 用户id * param string $permission 权限名 */ Yii::$app->authManager->checkAccess( $userId , $permission ) )
Readers who are interested in more Yii-related content can check out the special topics of this site: "Introduction to Yii Framework and Summary of Common Techniques", "Summary of Excellent Development Framework of PHP", "Basic Tutorial for Getting Started with Smarty Templates", "Introduction to PHP Object-Oriented Programming" Tutorial", "php string (string) usage summary", "php+mysql database operation introductory tutorial" and "php common database operation skills summary"
I hope this article will help you design PHP programs based on the Yii framework.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

Are you worried about WordPress backend garbled code? Try these solutions, specific code examples are required. With the widespread application of WordPress in website construction, many users may encounter the problem of garbled code in the WordPress backend. This kind of problem will cause the background management interface to display garbled characters, causing great trouble to users. This article will introduce some common solutions to help users solve the trouble of garbled characters in the WordPress backend. Modify the wp-config.php file and open wp-config.

How to remove jquery from yii2: 1. Edit the AppAsset.php file and comment out the "yii\web\YiiAsset" value in the variable $depends; 2. Edit the main.php file and add the configuration "'yii" under the field "components" \web\JqueryAsset' => ['js' => [],'sourcePath' => null,]," to remove the jquery script.

Title: Discuz background account login exception, how to deal with it? When you use the backend management of the Discuz forum system, you may sometimes encounter abnormal account login. This could be due to a variety of reasons, including a wrong password, account being blocked, network connection issues, etc. When encountering this situation, we need to solve the problem through simple troubleshooting and processing. Check whether the account number and password are correct: First, confirm whether the account number and password you entered are correct. When logging in, make sure the capitalization is correct and the password is

Discuz background login failed? Teach you how to solve it easily! As Discuz, as a popular forum platform, is widely used in website construction and management, sometimes you will encounter backend login failures, which is troubling. Today we will discuss the issues that may cause Discuz backend login failure, provide some solutions, and attach specific code examples. I hope this article can help webmasters and developers who encounter similar problems. 1. Troubleshooting is to solve the problem of Discuz background login failure.

How to disable software from running in the background in win11? We are using some software. When we are not using it, we will close the software. Some software will still run in the background after it is closed. During the process of running in the background, the computer will cause a certain amount of lag. Some friends want to know what should be done. How to disable software from running in the background in win11. The editor below has compiled the steps to disable software from running in the background in Win11. If you are interested, follow the editor and take a look below! Steps to disable software running in the background in win11: 1. Press the shortcut key "win+X" and select "Settings" from the options given above. 2. After entering the new interface, click "Apps" and then find "Applications and Features" on the right. 3. In it, find “Microsoft Information” and click

Switching between different applications is achieved through the front and back switching of processes. Background: After Linux starts a program, it switches to the background for execution and wants to continue operating in Linux. In Linux, you can use the following methods to start and exit a program in the background, but still keep its process running: 1. Linux starts a program to execute in the background 1. Use nohup and &: $nohupyour_program& Use the nohup command to make The program ignores the hang-up signal (SIGHUP) so that the program continues to run even if you exit the terminal. The & symbol causes the program to run in the background. 2. Use ctrl+Z: If you have started the program in the foreground, you can use ct

ThinkPHP6 backend management system development: Implementing backend functions Introduction: With the continuous development of Internet technology and market demand, more and more enterprises and organizations need an efficient, safe, and flexible backend management system to manage business data and conduct operational management. This article will use the ThinkPHP6 framework to demonstrate through examples how to develop a simple but practical backend management system, including basic functions such as permission control, data addition, deletion, modification and query. Environment preparation Before starting, we need to install PHP, MySQL, Com
