Yii2 set up backstage and realize RBAC rights control Complete example Tutorial _php instance

Source: Internet
Author: User
Tags php file yii

1. Installation Yii2

Not installed please refer to the simplest installation tutorials in the history of Yii2, without one

Installed please continue to see next steps

2. Configuration database

2.1 Configuration Database

Modify common/config/main-local.php The local database in the actual project is often inconsistent with the online database,

We are configured to main-local.php here, the product on the line, we can use git or svn ignore main-local.php, direct deployment online.

The MySQL database we use here is configured as follows


Of course, the information above the red circle needs to be manually modified by yourself, and if it's the same as mine, then you don't have to change it.

2.2 Create the User data table, we want to implement the background login behind

Description: The User table and menu table can be created to refer to the SQL in the component yii2-admin that we download later, the specific directory is located in

Vendor\mdmsoft\yii2-admin\migrations\schema-mysql.sql

CREATE TABLE ' user ' (
' id ' int () not NULL auto_  INCREMENT COMMENT ' Auto id ', 
' username ' varchar (255) NOT null COMMENT ' username ', 
' auth_key ' varchar () NOT NULL COMMENT ' Auto login key ', 
' password_hash ' varchar (255) Not NULL COMMENT ' encrypted password ', 
' password_reset_token ' varchar (255) DEFAULT Null COMMENT ' Reset password token ', 
' email ' varchar (255) NOT NULL COMMENT ' mailbox ', 
' role ' smallint (6) NOT null DEFAULT ' COM ment ' role level ', 
' status ' smallint (6) NOT null DEFAULT ' COMMENT ' state ', 
' created_at ' int (one) not null COMMENT ' creation time ', 
' updated_at ' int (one) not NULL COMMENT ' update Time ', 
PRIMARY KEY (' id ')
engine=innodb auto_increment=0 DEFAULT charset=utf8 comment= ' user table ';

2.3 Access to the Frontend site, first register a user

After the successful registration, the upper right corner will show the status of the landing, we will use the following users to register

Next we're going to start configuring the backend template.

3. Use Adminlte to render background template

Background template We use Adminlte (backend theme for Yii2 Framework)

Interrupt: Adminlte is a fully responsive admin template. Based on the BOOTSTRAP3 framework, easy to customize the template. Suitable for a wide range of screen resolutions, from small mobile devices to large desktops.

Several pages are built in, including dashboards, mailboxes, calendars, lock screens, logins and registrations, 404 errors, 500 errors, and so on.

3.1 Installation Adminlte

Https://github.com/dmstr/yii2-adminlte-asset

Open the link above and follow the steps to install

Here I briefly set down my own installation steps, after CD advanced,

Because it's a Mac, it's a direct composer to install.

Composer require dmstr/yii2-adminlte-asset "2.*"

After the installation is successful, there are several more folders under the vendor directory, as follows

3.2 YII2 Configuration Integration Adminlte, build a handsome on the background of the grade

Below we configure the next backend/config/main.php preview effect, small heart catch urgent want to taste the results

' Components ' => [' 
view ' => [' theme ' => [' Pathmap ' =>]
[' 
@app/views ' => ' @vendor/dmstr/ Yii2-adminlte-asset/example-views/yiisoft/yii2-app '],], [],]
,

Nice, the page instantly looks much better.

The problem is, we are in the components inside the theme, so to modify the layout of the file is very inconvenient, below we will not copy down the file to cover the layout of Yii.

Copy the layouts and site in the Vendor/dmstr/yii2-adminlte-asset/example-views/yiisoft/yii2-app directory

Overwrite the lauouts and site files in the backend/views/directory

After overwriting, remember to block out the configuration items for components view below

To this, the background of the template to come to an end, si not si very happy

4, the following we use Yii RBAC to achieve the background of the rights control

4.1 We first configure the short route

The compontents of the backend/config/main.php file plus the following configuration

The ' Urlmanager ' => [/ 
///is used to indicate urlmanager whether URL beautification is enabled, called the path format URL in Yii1.1,/// 
Yii2.0 is renamed Landscaping. 
///default not enabled. However, the actual use, especially the product environment, will generally be enabled. 
' Enableprettyurl ' => true,// 
whether strict parsing is enabled, such as enabling strict parsing, requires that the current request match at least 1 routing rules, 
//Otherwise considered an invalid route. 
//This option is only valid when Enableprettyurl is enabled. 
' enablestrictparsing ' => false, 
//whether to display the entry script in the URL. is to beautify the function of further supplement. 
' Showscriptname ' => false, 
//Specifies a suffix appended to the URL, such as. html. Valid only when Enableprettyurl is enabled. 
' 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 and add the following, which you can not create backend/web, it seems to be really need to hone the discipline OH

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< C7/>rewriterule. index.php

Of course, your Apache has to open the rewrite module.

Below we visit the following GII module test

Http://localhost/advanced/backend/web/gii

The checksum is OK.

4.2 Data tables needed to create a permission control

Of course, these yii2 are ready for us.

Open the Vendor/yiisoft/yii2/rbac/migrations/schema-mysql.sql file and create the datasheet in turn

' Auth_assignment ';
' Auth_item_child ';
' Auth_item ';
' Auth_rule ';

Additional menu menus, need to be created on your own

Description: User table and Menu table creation can refer to Vendor\mdmsoft\yii2-admin\migrations\schema-mysql.sql

CREATE TABLE ' menu ' ( 
' id ' int () NOT NULL auto_increment, 
' name ' varchar (128) NOT NULL, 
' parent ' int (one) DEF Ault null, 
' route ' varchar (256) default NULL, 
' order ' int (one) 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 Download installation yii2-admin

Reference Https://github.com/mdmsoft/yii2-admin

Follow the steps step-by-step installation, with Adminlte installation

We'll see the Mdmsoft directory below the vendor directory.

4.4 Permissions Configuration

Open backend/config/main.php Modify Configuration

' Modules ' => [' 
admin ' => [' 
class ' => ' Mdm\admin\module ', 
],
],
' aliases ' => [ 
' @ Mdm/admin ' => ' @vendor/mdmsoft/yii2-admin ',
],
//Here must add the AuthManager configuration item
' components ' => [ 
... 
//components Array of AuthManager components, there are phpmanager and Dbmanager two ways, 
//phpmanager the permission relationship in the file, where the use of the Dbmanager method , save the permission relationship in the database. 
' AuthManager ' => [' 
class ' => ' Yii\rbac\dbmanager ', 
' defaultroles ' => [' guest '], 
], 
...
],

4.5 We access under the Permission module test how the effect

Http://localhost/advanced/backend/web/admin/route

Well, the interface is there, the following we speed up the pace of acceptance of our authority this piece of the end or not?

Generally, it's OK to do this step. The following can be groped to add the route assignment permissions.

Below we on the left menu on the permission of the column plus, the code can be copied directly, placed in the <section class= "sidebar" ></section>

<ul class= "Sidebar-menu" > <li class= "TreeView" > <a href= "#" > <i class= "fa fa-gears" ></i> <span> Permissions Control </span> <i class= "fa fa-angle-left pull-right" ></i> </a> <ul class= "Treevi Ew-menu "> <li class=" TreeView "> <a href="/admin "> Admin </a> <ul class=" Treeview-menu "> <li ><a href= "/user" ><i class= "fa fa-circle-o" ></i> backend user </a></li> <li class= " TreeView "> <a href="/admin/role "> <i class=" fa fa-circle-o "></i> permissions <i class=" FA fa-angle-left P Ull-right "></i> </a> <ul class=" Treeview-menu "> <li><a href="/admin/route "><i class= "FA fa-circle-o" ></i> routing </a></li> <li><a href= "/admin/permission" ><i class= "FA fa-circle-o" ></i> permissions </a></li> <li><a href= "/admin/role" ><i class= "FA Fa-circle-o "></i> role </a></li> <li&Gt;<a href= "/admin/assignment" ><i class= "fa fa-circle-o" ></i> distribution </a></li> <li> <a href= "/admin/menu" ><i class= "fa fa-circle-o" ></i> menu </a></li> </ul> </li > </ul> </li> </ul> </li> </ul>

Let's take a look at the effect chart, so we can make it easy to manipulate the permissions.

In this way, our rights control is basically over, and the permissions need to be explained:

You should add the route first, then add the name of the permission, and then assign a separate permission to the role or individual.

5. How to use menu to control menus?

4.5 Steps We are directly to write UL Li's Way to the left menu to operate , this is also able to achieve through the menu to control the Permissions drop.

But Nan, one inconvenient operation, and to increase the modification of what Dongdong need us to modify the implementation of the program, which also TTM inconvenient. Fortunately, our family has a coup, DDV kill kill.

Well, it's a long way off. In retrospect, was it the 123456 tables we created and a menu table that was not used? How do you use the goods? Come on, let's get back to business.

First choice, we visit/admin/menu/index add a few levels of menu, called First Level 1, Level 2, Level 3 bar, oh yes, forget to add routes, what's going on, we first visit the/admin/route/index to the left side of the route to the right, Otherwise, creating a new menu will fail. When creating a menu, [map] [data] we do not fill in.

After adding, we open the layout file Left.php,use two class files, respectively, Yii\bootstrap\nav and Mdm\admin\components\menuhelper;

Get permission Actions Menuhelper::getassignedmenu all help us to do it.

OK, let's delete the 4.5 added Sidebar-menu menu and try to add the following code

Echo Nav::widget (
[
' Encodelabels ' => false,
' options ' => [' class ' => ' Sidebar-menu '],
' Items ' => menuhelper::getassignedmenu (Yii:: $app->user->id),
]
);

Now Menu control permissions We are basically OK, now you can continue to add the menu to try how the effect.

Here, our background and RBAC rights control can be said to be very perfect, if you are in the process of trying to encounter any problems, the following message is good, we share the discussion.

Related reading:

Yii2 RBAC Privilege Control Menu Instance Tutorial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.