yii2筹建完美后台并实现rbac权限控制案例教程
yii2搭建完美后台并实现rbac权限控制案例教程
作者:白狼 出处:www.manks.top/article/yii2_frame_rbac_template
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
1、安装yii2
未安装的请参考yii2史上最简单式安装教程,没有之一
已安装的请继续看下一步操作
2、配置数据库
2.1 配置数据库
修改common/config/main-local.php 实际项目中本地的数据库往往跟线上数据库不一致,
我们这里配置到main-local.php就可以了,产品上线后,我们可以使用git或者svn忽略掉main-local.php,线上直接部署。
我们这里使用的mysql数据库,配置如下
当然啦,上面红圈圈的信息需要你自己手动修改掉,要是十分巧合跟我的一样那就不用在修改了
2.2 创建user数据表,我们后面要实现后台登陆
说明:user表和menu表的创建可以参考我们后面下载的组件yii2-admin里面的sql,具体目录位于
vendor\mdmsoft\yii2-admin\migrations\schema-mysql.sql
CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增ID', `username` varchar(255) NOT NULL COMMENT '用户名', `auth_key` varchar(32) NOT NULL COMMENT '自动登录key', `password_hash` varchar(255) NOT NULL COMMENT '加密密码', `password_reset_token` varchar(255) DEFAULT NULL COMMENT '重置密码token', `email` varchar(255) NOT NULL COMMENT '邮箱', `role` smallint(6) NOT NULL DEFAULT '10' COMMENT '角色等级', `status` smallint(6) NOT NULL DEFAULT '10' COMMENT '状态', `created_at` int(11) NOT NULL COMMENT '创建时间', `updated_at` int(11) NOT NULL COMMENT '更新时间', PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT='用户表';
2.3 访问frontend站点,先注册个用户
注册成功后,右上角会显示登陆的状态,我们后面会用到这个注册的用户
接下来我们要开始配置后台的模板了。
3、利用AdminLTE渲染后台模板
后台的模板我们采用利用 AdminLTE(Backend theme for Yii2 Framework)
插播一曲:AdminLTE是一个完全响应管理模板。基于Bootstrap3框架,易定制模板。适合多种屏幕分辨率,从小型移动设备到大型台式机。
内置了多个页面,包括仪表盘、邮箱、日历、锁屏、登录及注册、404错误、500错误等页面。
3.1 安装AdminLTE
https://github.com/dmstr/yii2-adminlte-asset
打开上面的链接,按照操作步骤进行安装
这里我简述下自己的安装步骤,cd advanced后,
因为是mac,这里直接composer进行安装就行了composer require dmstr/yii2-adminlte-asset "2.*"
安装成功后,vendor目录下会多几个文件夹,如下
3.2 yii2配置整合AdminLTE,搭建帅气上档次的后台
下面我们配置下backend/config/main.php先预览下效果,小心脏捉急的巴不得赶紧尝尝战果
'components' => [ 'view' => [ 'theme' => [ 'pathMap' => [ [email protected]/views' => [email protected]/dmstr/yii2-adminlte-asset/example-views/yiisoft/yii2-app' ], ], ],],
nice,页面瞬间好看多了。
问题来了,我们是在components里面单独配置的theme,这样以后要修改布局文件什么的是很不方便滴,下面我们把不局文件拷贝下来覆盖掉yii自带的layout.
把vendor/dmstr/yii2-adminlte-asset/example-views/yiisoft/yii2-app目录下的layouts和site拷贝
覆盖掉backend/views/目录下的lauouts和site对应的文件
覆盖后记得屏蔽掉 components下面view的配置项
到此,后台模板的搭建告一段落,si不si很happy
4、下面我们用yii的rbac实现后台的权限控制
4.1 我们先配置下简短路由
backend/config/main.php文件的compontents加上下面的配置
'urlManager' => [ //用于表明urlManager是否启用URL美化功能,在Yii1.1中称为path格式URL, // Yii2.0中改称美化。 // 默认不启用。但实际使用中,特别是产品环境,一般都会启用。 'enablePrettyUrl' => true, // 是否启用严格解析,如启用严格解析,要求当前请求应至少匹配1个路由规则, // 否则认为是无效路由。 // 这个选项仅在 enablePrettyUrl 启用后才有效。 'enableStrictParsing' => false, // 是否在URL中显示入口脚本。是对美化功能的进一步补充。 'showScriptName' => false, // 指定续接在URL后面的一个后缀,如 .html 之类的。仅在 enablePrettyUrl 启用时有效。 'suffix' => '', 'rules' => [ "<controller:>/<id:>"=>"<controller>/view", "<controller:>/<action:>"=>"<controller>/<action>" ],],</action></controller></action:></controller:></controller></id:></controller:>
接下来在项目的根目录 backend/web下面创建.htaccess文件并添加如下内容,这个文件你都创建不下来,看来是真需要再磨练磨练哦
Options +FollowSymLinksIndexIgnore */*RewriteEngine on# if a directory or a file exists, use it directlyRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d# otherwise forward it to index.phpRewriteRule . index.php
当然,你的apache必须要开启rewrite模块。
下面我们访问下gii模块测试下
http://localhost/advanced/backend/web/gii
校验是可以的。
4.2 创建权限控制所需要的数据表
当然,这些yii2都给我们准备好了。
打开 vendor/yiisoft/yii2/rbac/migrations/schema-mysql.sql 文件,依次创建数据表
`auth_assignment`;`auth_item_child`;`auth_item`;`auth_rule`;另外补充菜单menu表,需要的自行创建说明:user表和menu表的创建可以参考 vendor\mdmsoft\yii2-admin\migrations\schema-mysql.sqlCREATE TABLE `menu` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(128) NOT NULL, `parent` int(11) DEFAULT NULL, `route` varchar(256) DEFAULT NULL, `order` int(11) DEFAULT NULL, `data` text, PRIMARY KEY (`id`), KEY `parent` (`parent`), CONSTRAINT `menu_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `menu` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8
4.3 下载安装 yii2-admin
参考 https://github.com/mdmsoft/yii2-admin
按照步骤一步一步安装即可,同adminlte的安装
安装好了我们会在vendor目录下面看到 mdmsoft目录
4.4 权限配置
打开backend/config/main.php修改配置
'modules' => [ 'admin' => [ 'class' => 'mdm\admin\Module', ],],'aliases' => [ [email protected]/admin' => [email protected]/mdmsoft/yii2-admin',],//这里必须添加authManager配置项'components' => [ ... //components数组中加入authManager组件,有PhpManager和DbManager两种方式, //PhpManager将权限关系保存在文件里,这里使用的是DbManager方式,将权限关系保存在数据库. 'authManager' => [ 'class' => 'yii\rbac\DbManager', 'defaultRoles' => ['guest'], ], ...],
4.5 我们访问下权限模块检验下效果如何
http://localhost/advanced/backend/web/admin/route
嗯,界面是有的了,下面我们加快脚步验收下我们的权限这块到底成还是不成呢?
一般来说到这一步就ok的了。后面的可以自己摸索着添加路由分配权限了。
下面我们在左侧菜单上把权限的栏目加上,代码可直接复制,放置于 内
我们看下效果图,这样一来,我们对权限进行操作就十分的方便了
如此,我们的权限控制基本告一段落了,关于权限需要说明的是:
你应该先添加路由,然后添加权限名称,后再对角色或个人进行权限的独立分配。
5、如何利用menu对菜单进行控制?
4.5步骤中我们是直接写ul li的方式对左侧菜单进行操作的,这样也是能够实现通过菜单对权限进行控制滴。但是喃,一来不方便操作,而来增加修改个什么东东都得需要我们去修改程序实现,这也TTM不方便了。还好我们家有妙招,DDV杀杀杀。
好了,又扯远了。仔细回想,是不是我们创建的123456张表还有一张menu表没有利用到喃?这货怎么利用喃?来,我们回归正题。
首选,我们访问/admin/menu/index添加几个一级菜单,姑且叫做一级1,一级2,一级3吧,哦对了,忘记添加路由了,怎么回事呢,我们先访问/admin/route/index 把左侧的路由移动到右侧,不然上面创建新菜单会失败哦。创建菜单时,[映射][数据]我们暂且不填写。
添加完毕之后呢,我们打开布局文件left.php,use两个类文件,分别是yii\bootstrap\Nav和mdm\admin\components\MenuHelper;
获取权限的操作 MenuHelper::getAssignedMenu都帮我们做好了。
ok,我们删掉4.5添加的sidebar-menu菜单,添加下面的代码试试看
echo Nav::widget( [ 'encodeLabels' => false, 'options' => ['class' => 'sidebar-menu'], 'items' => MenuHelper::getAssignedMenu(Yii::$app->user->id), ]);
现在菜单控制权限我们基本上是ok了,现在你可以继续添加菜单试试效果如何。
到此呢,我们的后台和rbac的权限控制可以说是做得非常完美了,如果你在尝试的过程中遇到任何问题,下面留言就好,咱们共同交流探讨。
- 1楼xchsp
- 谢谢分享

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



Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Concepts and instances of classes and methods Class (Class): used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection. Objects are instances of classes. Method: Function defined in the class. Class construction method __init__(): The class has a special method (construction method) named init(), which is automatically called when the class is instantiated. Instance variables: In the declaration of a class, attributes are represented by variables. Such variables are called instance variables. An instance variable is a variable modified with self. Instantiation: Create an instance of a class, a specific object of the class. Inheritance: that is, a derived class (derivedclass) inherits the base class (baseclass)

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

Class is a keyword in Python, used to define a class. The method of defining a class: add a space after class and then add the class name; class name rules: capitalize the first letter. If there are multiple words, use camel case naming, such as [class Dog()].

jQuery is a classic JavaScript library that is widely used in web development. It simplifies operations such as handling events, manipulating DOM elements, and performing animations on web pages. When using jQuery, you often encounter situations where you need to replace the class name of an element. This article will introduce some practical methods and specific code examples. 1. Use the removeClass() and addClass() methods jQuery provides the removeClass() method for deletion

When writing PHP code, using classes is a very common practice. By using classes, we can encapsulate related functions and data in a single unit, making the code clearer, easier to read, and easier to maintain. This article will introduce the usage of PHPClass in detail and provide specific code examples to help readers better understand how to apply classes to optimize code in actual projects. 1. Create and use classes In PHP, you can use the keyword class to define a class and define properties and methods in the class.

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships
