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
- 谢谢分享

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.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


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

Atom editor mac version download
The most popular open source editor

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.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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

Dreamweaver CS6
Visual web development tools