


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.

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software