yii2搭建完美后台并实现rbac权限控制, refernce: http://www.manks.top/yii2_frame_rbac_template.html
1. 安装yii2 advanced
composer create-project --prefer-dist yiisoft/yii2-app-advanced advanced
cd advanced
php init
vim common/config/main-local.php //配置数据库访问信息
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2advdev',
'username' => 'root',
'password' => '123456',
'charset' => 'utf8',
],
./yii migrate //创建user 表,前台注册登录
localhost/advanced/frontend/web
localhost/advanced/backend/web
2. 利用AdminLTE渲染后台模板
cd advanced
composer require dmstr/yii2-adminlte-asset "2.*"
拷贝 vendor/dmstr/yii2-adminlte-asset/example-views/yiisoft/yii2-app 目录下的layouts和site目录以及文件
覆盖掉backend/views/目录下的lauouts和site对应的文件
3.完善rbac权限管理
3.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:\w+>/<id:\d+>"=>"<controller>/view",
"<controller:\w+>/<action:\w+>"=>"<controller>/<action>"
],
],
3.2 配置apache web server
在应用的目录 backend/web下面创建.htaccess文件并添加如下内容
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
3.3 apache support rewrite
cd /etc/apache2
a2enmod rewrite
执行后会在mods-available目录下创建一个快捷方式,连接到mods-enabled下rewrite模块。
Rewrite库加载不代表我们的.htaccess文件就能生效,还需要专门打开指定目录的AllowOveride开关,apache2.conf(AllowOverride None 修改为: AllowOverride All), 或者sites-enabled/000-default, 将其中的 AllowOverride None 修改为: AllowOverride All
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride all
Require all granted
</Directory>
service apache2 restart
http://localhost/advanced/backend/web/gii
gii模块仅限本地访问,默认得用127.0.0.1或者localhost地址.
可以正常打开即没问题。
3.4 下载安装 yii2-admin
cd advanced
composer self-update
composer install --prefer-dist
composer update
composer require mdmsoft/yii2-admin "~2.0"
安装好了可以在 vendor 目录下看到 mdmsoft 目录
3.5 权限配置
打开backend/config/main.php 修改配置
我在安装的时候遇到问题,rbac迁移的时候报异常,在官网(http://www.yiiframework.com/doc-2.0/guide-security-authorization.html)找到这个:
Note: If you are using yii2-basic-app template, there is a config/console.php configuration file where the authManager needs to be declared additionally to config/web.php. In case of yii2-advanced-app the authManager should be declared only once in common/config/main.php.
把authManager配置项移到common/config/main.php就好了!!!!