


Yii2 rbac permission control rule tutorial detailed explanation_php example
In our previous complete tutorial on setting up the backend of Yii2 and implementing rbac permission control, I wonder if you have ever wondered what the rule table does. Why did we not involve this table in the whole process?
Believe me, if I don’t tell you, some people will try Baidu or Google, but in the end they will just draw water from a bamboo basket. There is very little content to explain in this part!
For general permission systems, the rbac we made before is generally sufficient. Even without rules, I believe you can also achieve the functions we use rules to achieve.
We will give a specific operation tutorial using the example from the official website to see what this mysterious rule does!
Depending on demand:
We have administrators and ordinary users. For the article system, we allow administrators to do any operation on articles, but only ordinary users are allowed to create articles and modify articles created by themselves. Note that they are allowed to modify articles created by themselves. Articles are not allowed to be modified, nor are all articles allowed to be modified!
Let’s see how to implement the yii2 rbac rule. The focus is to teach everyone how to use this rule, and also to solve the knots in many people’s minds!
Before we add a rule, we need to implement the execute method of the yiirbacRule class.
<?php namespace backend\components; use Yii; use yii\rbac\Rule; class ArticleRule extends Rule { public $name = 'article'; public function execute($user, $item, $params) { // 这里先设置为false,逻辑上后面再完善 return false; } }
Then, we can go to the background rule list (/admin/rule/index) to add rules. For specific adding methods, please refer to the screenshot below
Note that many people will fail in adding the class name in the above step. Remember to add the namespace where our ArticleRule file is located!
Let’s look at the third step, which is also where it’s easy to make mistakes! Please pay attention to this tutorial, high energy lies ahead!
We added a new permission to the access permission list (/admin/permission/index). This permission is only for modifying articles, and then we assign it to the user's role
Please note that there is a serious warning here. The route controlled by the newly added permissions here is the update operation of the article (/article/update). It is assigned to the current user only once. The current operation is assigned repeatedly to the role or user to which it belongs. , which may cause the rule to fail, and the reason for the failure is overwriting!
At this moment, refresh the article update page (/article/update/1) again. Obviously, we are directly given a 403 forbidden no access prompt, which means that the rule we just added has taken effect! If it does not take effect at this moment, please check the two points mentioned above!
Then we implement the business logic in the ArticleRule::execute method, please refer to the following:
class ArticleRule extends Rule { public $name = 'article'; /** * @param string|integer $user 当前登录用户的uid * @param Item $item 所属规则rule,也就是我们后面要进行的新增规则 * @param array $params 当前请求携带的参数. * @return true或false.true用户可访问 false用户不可访问 */ public function execute($user, $item, $params) { $id = isset($params['id']) ? $params['id'] : null; if (!$id) { return false; } $model = Article::findOne($id); if (!$model) { return false; } $username = Yii::$app->user->identity->username; $role = Yii::$app->user->identity->role; if ($role == User::ROLE_ADMIN || $username == $model->operate) { return true; } return false; } }
The last step is verification. Has the rule authentication we implemented worked?
The test steps are as follows for reference:
1. The current user creates an article. Remember to record the creator of the current article. His role is the administrator. Our default is User::ROLE_ADMIN
2. Create an ordinary user and create an article. You also need to record the creator of the current article
3. Use the administrator account and the ordinary user to log in to the system to modify these two articles. The conclusion is naturally to meet the needs we mentioned at the beginning. The administrator can modify both articles, and ordinary users can only modify their own articles.
The above is the detailed explanation of the rules tutorial for Yii2 rbac permission control introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the Script House website!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
