Author: Bai Lang Source: www.manks.top/article/yii2_frame_rbac_template
The copyright of this article belongs to the author, and you are welcome to reprint it. However, this statement must be retained without the author's consent, and a link to the original text must be provided in an obvious position on the article page. Otherwise, we reserve the right to pursue legal liability.
If you haven’t installed it yet, please refer to the simplest installation tutorial in the history of yii2, there is no one else
If you have already installed it, please continue to the next step
Modify common/config/main-local.php. In actual projects, the local database is often inconsistent with the online database.
We only need to configure main-local.php here. After the product is online, we can use git or svn to ignore main-local.php and deploy it directly online.
The mysql database we use here is configured as follows
Of course, the information circled in red above needs to be modified manually. If by chance it is the same as mine, there is no need to modify it
Note: To create the user table and menu table, you can refer to the sql in the component yii2-admin we downloaded later. The specific directory is located in
vendormdmsoftyii2-adminmigrationsschema-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='用户表';
After successful registration, the login status will be displayed in the upper right corner. We will use this registered user later
Next we have to configure the background template.
We use AdminLTE (Backend theme for Yii2 Framework) for the background template
A quick aside: AdminLTE is a fully responsive admin template. Based on the Bootstrap3 framework, it is easy to customize the template. Fits a variety of screen resolutions, from small mobile devices to large desktops.
Built-in multiple pages, including dashboard, email, calendar, lock screen, login and registration, 404 error, 500 error and other pages.
https://github.com/dmstr/yii2-adminlte-asset
Open the link above and follow the steps to install
Here I will briefly describe my installation steps. After cd advanced,
因为是mac,这里直接composer进行安装就行了 composer require dmstr/yii2-adminlte-asset "2.*"
After successful installation, there will be several more folders in the vendor directory, as follows
Let’s configure backend/config/main.php and preview the effect first. Those who are anxious can’t wait to try the results
'components' => [ 'view' => [ 'theme' => [ 'pathMap' => [ '@app/views' => '@vendor/dmstr/yii2-adminlte-asset/example-views/yiisoft/yii2-app' ], ], ], ],
Nice, the page looks much better instantly.
Here comes the problem. We configure the theme separately in components, so it is very inconvenient to modify the layout file in the future. Next, we copy the non-local files and overwrite the layout that comes with Yii.
Copy the layouts and site in the vendor/dmstr/yii2-adminlte-asset/example-views/yiisoft/yii2-app directory
Overwrite the files corresponding to lauouts and site in the backend/views/ directory
After overwriting, remember to block the configuration items of the view under components
At this point, the construction of the background template has come to an end, I am very happy
The components of the backend/config/main.php file plus the following configuration
'urlManager' => [ //用于表明urlManager是否启用URL美化功能,在Yii1.1中称为path格式URL, // Yii2.0中改称美化。 // 默认不启用。但实际使用中,特别是产品环境,一般都会启用。 'enablePrettyUrl' => true, // 是否启用严格解析,如启用严格解析,要求当前请求应至少匹配1个路由规则, // 否则认为是无效路由。 // 这个选项仅在 enablePrettyUrl 启用后才有效。 'enableStrictParsing' => false, // 是否在URL中显示入口脚本。是对美化功能的进一步补充。 'showScriptName' => false, // 指定续接在URL后面的一个后缀,如 .html 之类的。仅在 enablePrettyUrl 启用时有效。 'suffix' => '', 'rules' => [ "<controller:\w+>/<id:\d+>"=>"<controller>/view", "<controller:\w+>/<action:\w+>"=>"<controller>/<action>" ], ],
Next, create the .htaccess file under the root directory of the project, backend/web, and add the following content. You can’t even create this file. It seems that you really need to hone it again
Options +FollowSymLinks IndexIgnore */* RewriteEngine on # if a directory or a file exists, use it directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # otherwise forward it to index.php RewriteRule . index.php
Of course, your apache must enable the rewrite module.
Let’s access the gii module and test it
http://localhost/advanced/backend/web/gii
Verification is possible.
Of course, these yii2 have been prepared for us.
Open the vendor/yiisoft/yii2/rbac/migrations/schema-mysql.sql file and create the data table in sequence
`auth_assignment`; `auth_item_child`; `auth_item`; `auth_rule`; 另外补充菜单menu表,需要的自行创建 说明:user表和menu表的创建可以参考 vendor\mdmsoft\yii2-admin\migrations\schema-mysql.sql CREATE 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
Reference https://github.com/mdmsoft/yii2-admin
Follow the steps to install step by step, the same as the installation of adminlte
After installation, we will see the mdmsoft directory under the vendor directory
Open backend/config/main.php to modify the configuration
'modules' => [ 'admin' => [ 'class' => 'mdm\admin\Module', ], ], 'aliases' => [ '@mdm/admin' => '@vendor/mdmsoft/yii2-admin', ], //这里必须添加authManager配置项 'components' => [ ... //components数组中加入authManager组件,有PhpManager和DbManager两种方式, //PhpManager将权限关系保存在文件里,这里使用的是DbManager方式,将权限关系保存在数据库. 'authManager' => [ 'class' => 'yii\rbac\DbManager', 'defaultRoles' => ['guest'], ], ... ],
http://localhost/advanced/backend/web/admin/route
Well, the interface is there. Let’s speed up the process and check whether our permissions are successful or not?
一般来说到这一步就ok的了。后面的可以自己摸索着添加路由分配权限了。
下面我们在左侧菜单上把权限的栏目加上,代码可直接复制,放置于 内
<ul class="sidebar-menu"> <li class="treeview"> <a href="#"> <i class="fa fa-gears"></i> <span>权限控制</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li class="treeview"> <a href="/admin">管理员</a> <ul class="treeview-menu"> <li><a href="/user"><i class="fa fa-circle-o"></i> 后台用户</a></li> <li class="treeview"> <a href="/admin/role"> <i class="fa fa-circle-o"></i> 权限 <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="/admin/route"><i class="fa fa-circle-o"></i> 路由</a></li> <li><a href="/admin/permission"><i class="fa fa-circle-o"></i> 权限</a></li> <li><a href="/admin/role"><i class="fa fa-circle-o"></i> 角色</a></li> <li><a href="/admin/assignment"><i class="fa fa-circle-o"></i> 分配</a></li> <li><a href="/admin/menu"><i class="fa fa-circle-o"></i> 菜单</a></li> </ul> </li> </ul> </li> </ul> </li> </ul>
我们看下效果图,这样一来,我们对权限进行操作就十分的方便了
如此,我们的权限控制基本告一段落了,关于权限需要说明的是:
你应该先添加路由,然后添加权限名称,后再对角色或个人进行权限的独立分配。
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的权限控制可以说是做得非常完美了,如果你在尝试的过程中遇到任何问题,下面留言就好,咱们共同交流探讨。