Yii2 frontend and backend separation and use of migrate (7), yii2migrate_PHP tutorial

Source: Internet
Author: User
Tags php foreach
Yii2 frontend and backend separation and migrate (7), yii2migrate. Yii2 frontend and backend separation and use of migrate (7), yii2migrate has been busy with other tasks recently (in fact, it is lazy !), I have read Yii2 in depth, some of which were not clear at the beginning are a little clear about the frontend and backend separation of Yii2 and the use of migrate (7), yii2migrate

I have been busy with other tasks recently (in fact, I am lazy !), I read Yii2 in depth, but I am a little clear about what I didn't understand at the beginning, and then I see yii2's image uploading, processing, rich text, restful, etc, however, since this is not done here, it does not work, so we should follow the steps step by step, first talk about the front and back-end separation. (In fact, the general content management site does not need to be completely separated or anything described below. it's okay to look at it)

I personally think there are several situations in the front and back ends. The first is whether the front and back ends use a verification system, and the second is whether the front and back ends share a data table.

Generally, the following three methods are commonly used:

A. share A verification system and A data table.

B. Two verification systems and one data table.

C. Two verification systems and two data tables.

In Yii2 advanced edition, the default type is A, that is, the data table is the same, and the login/logout is performed on one side and the login/logout is performed on the other side. this structure is suitable for forums, the administrator also needs to have the same post and reply functions as the members, and the table fields are basically the same. (in my opinion, after all, there are not many contacts, and different background building topics have also been searched on the Internet, but it is rarely discussed in detail). In this way, the front and back ends can be distinguished by fields and permissions. What we will do is the C type, such as some e-commerce websites. the functions of the background administrator and the front-end members are too different, and the table fields are also different, so the verification system is different, it is better to put two data tables. B is a simplified version of C. If C is set, B is the same.

First, create an admin table to store administrator data, and the members still use the original user table. here we use the migrate of yii to create the table, which has been mentioned in the Yii2 initialization section, here we will explain in detail:

1. run the command before version 2.07 of yii2 to create a php file in the console/migrations directory, and then write the create table statement under the file.

Yii migrate/create admin

2. after yii2 version 2.07, more detailed categories are added. for example, I have created an admin table, but a status field is missing, then I can directly use the following command to generate a file that only adds fields.

Yii migrate/create add_column_to_admin -- fields = status: int (10): nontNull

Generation:

<?phpuse yii\db\Migration;class m160501_053640_add_column_to_admin extends Migration{public function up(){$this->addColumn('admin', 'status', $this->int(10)->nontNull());}public function down(){$this->dropColumn('admin', 'status');}}

For more information, see the original code in the actionCreate method in the file vendor/yiisoft/yii2/console/BaseMigrateController. php:

} elseif (preg_match('/^add_(.+)_to_(.+)$/', $name, $matches)) {$content = $this->renderFile(Yii::getAlias($this->generatorTemplateFiles['add_column']), ['className' => $className,'table' => mb_strtolower($matches[2], Yii::$app->charset),'fields' => $this->fields]);}

As we can see, here is the regular expression matching add_xxx_to_xxx to determine which template to point to and generate different styles.

Match these styles according to the parameters following migrate/create:

1. create_junction _ table name_and_table name, used to create a join table

2. add_xxx_to _ table name, used to add a field (you can use the -- fields style to specify a field. Otherwise, an empty field is generated and must be written by yourself. of course, you can also add a comment example to the template)

3. drop_xxx_from _ table name, used to delete a field (same as above)

4. create _ table name, used to create a table

5. drop _ table name, used to delete a table

Note: You can use yii help migrate on the console to view more usage information.

The template file can be found in the vendor/yiisoft/yii2/views file. if you want to change the template and make it more suitable for your operations, you can do this:

Create the views folder in the console file, copy the template you want to modify above to modify it, and then modify it in console/config/main. php.

Return [// modify the migration template 'controllermap' => ['migrate' => ['class' => 'yii \ console \ controllers \ migratecontroller ', 'templatefile '=>' @ yii/views/migration. php ', // Default Template. 'generatortemplatefiles' => ['create _ table' =>' @ console/views/createTableMigration should be rarely used after 2.07. php ', // modify 'drop _ table' =>' @ yii/views/dropTableMigration. php ', // unmodified 'add _ column' =>' @ console/views/addColumnMigration. php ', // modify 'drop _ column' =>' @ console/views/dropColumnMigration. php ', // modify 'create _ junction' => '@ yii/views/createJunctionMigration. php '// unmodified],];

It is worth noting that in the generatorTemplateFiles configuration, all five files must be written completely. if not modified, write the original path, the original path can be in the vendor/yiisoft/yii2/console/MigrateController. php. Otherwise, an error will be reported when you use the unwritten command template.

As for how to write specific statements such as creating tables and adding fields, there are actually two different versions (2.06 new writing, here we will not look at the Chinese version of yii2 without updating the guide. we will directly look at the updated English version. click here, which includes the content mentioned above and the specific writing method. It took a lot of time for google to search and follow the source code to understand the principles described above. later, I saw the tragedy in the English version, in addition, I recently did not search for any keyword in the api documentation on the Yii official website. I don't know if it is a problem or a problem on the official website, you can only compare the Chinese guide with the English guide to see which one corresponds. Therefore, it would be better to speak English. read the English documents directly.

At present, I have modified create_table by adding table comments and segment comments (this search and query source code did not find a similar-> comment writing method, it may be to be compatible with other databases, so it can only be spliced, however, when gii generates a model, the attributeLabels method can directly display the corresponding Chinese name based on the annotation.) an example comment is added to the add_column and drop_column templates, it is easy to forget to write with reference to the annotation example when using it, and you do not need to add the -- fileds parameter. Er, paste your template and the admin table statement that should be created here:

Template createTableMigration. php:

<? Php/*** This view is used by console/controllers/MigrateController. php * The following variables are available in this view: * // * @ var $ className string the new migration class name * // * @ var $ table string the name table * // * @ var $ fields array the fields */echo "<? Php \ n ";?> Use yii \ db \ Migration; class <? = $ ClassName?> Extends Migration {const TBL_NAME = '{{% <? = $ Table?> }} '; Public function up () {$ tableOptions = null; if ($ this-> db-> driverName = 'mysql ') {$ tableOptions = 'character SET utf8 COLLATE utf8_general_ci ENGINE = InnoDB COMMENT = "fill in table COMMENT" ';} $ this-> createTable (self: TBL_NAME, [<? Php foreach ($ fields as $ field):?> <? Php if ($ field = end ($ fields):?> '<? = $ Field ['properties']?> '=> $ This-> <? = $ Field ['recorator']. ". \" comment' fill in the segment COMMENT '\ "". "\ n"?> <? Php else:?> '<? = $ Field ['properties']?> '=> $ This-> <? = $ Field ['recorator']. ". \" comment' fill in the segment COMMENT '\ "". ", \ n"?> <? Php endif;?> <? Php endforeach;?>], $ TableOptions);} public function down () {$ this-> dropTable (self: TBL_NAME );}}

Specific statement m160326_133655_create_admin.php:

<? Phpuse yii \ db \ Migration; class m160427_133556_create_admin extends Migration {const TBL_NAME = '{{% admin}'; public function up () {$ tableOptions = null; if ($ this-> db-> driverName = 'mysql') {$ tableOptions = 'character SET utf8 COLLATE utf8_general_ci ENGINE = InnoDB COMMENT = "background administrator table "';} $ this-> createTable (self: TBL_NAME, ['id' => $ this-> primaryKey (), 'username' => $ this-> string () -> notNull ()-> unique (). "COMMENT 'username'", 'auth _ key' => $ this-> string (32)-> notNull (). "COMMENT 'authentication key'", 'password _ hash' => $ this-> string ()-> notNull (). "COMMENT 'password'", 'password _ reset_token '=> $ this-> string ()-> unique (). "COMMENT 'password reset token'", 'Email '=> $ this-> string ()-> notNull ()-> unique (). "COMMENT 'mailbox '", 'status' => $ this-> smallInteger ()-> notNull ()-> defaultValue (10 ). "COMMENT 'status'", 'created _ at' => $ this-> integer ()-> notNull (). "COMMENT 'creation time'", 'updated _ at' => $ this-> integer ()-> notNull (). "COMMENT 'update time'",], $ tableOptions);} public function down () {$ this-> dropTable (self: TBL_NAME );}}

Continue to run the following command line code to generate the admin table. because it is only for demonstration, the admin and user tables are basically the same and do not care about these details.

Yii migrate

Now, after two tables are generated, we need to completely separate the foreground logon and background logon:

1. front-end modification: because it is no longer public, first set the User in the common/models public. php and LoginForm. move php to frontend/models. By the way, change the namespace of the two files to start with frontend and read the entire front-end file, change all the namespaces involved in the two common files to the front-end namespace.

2. background modification: You also need to have the two files Admin in backend/models. php and LoginForm. php, which can be generated using Gii (note that you must inherit IdentityInterface, implement methods in this interface, and refer to User. php to implement the relevant login registration method), you can also directly copy the two files above (the User. php is renamed Admin. php. make sure that the names or numbers of fields in the user and admin tables are consistent. php ). Since we have previously created GRUD in the background, there are many changes here (searchModel, controller, and view must be changed to admin). We recommend that you preview the files generated by Gii. Well, if we need to separate the front and back ends, this chapter should be placed in front of Chapter 5, so we don't need to change this much in the background.

Now, you can log on to the front and back ends and try again. Although the background table has been created but no administrator has been added, the background cannot be created because it has been logged on to the back end, and the registration function is not available (in this case, there is generally no need to have the registration function in the background), so here we continue to use the console function to create a user, the console has a lot of features, for more information about database management, click here.

Create an InitController in console/controllers and run the following code:

<? Php/*** Application initialization * For more information, see Yii2.0 Video Tutorial */namespace console \ controllers; use backend \ models \ Admin; class InitController extends \ yii \ console \ Controller {/*** Create init admin */public function actionAdmin () {echo "Create init admin... \ n "; // prompt for the current operation $ username = $ this-> prompt ('admin Name :'); // receiving username $ email = $ this-> prompt ('email: '); // receiving Email $ password = $ this-> prompt ('password :'); // receive password $ mo Del = new Admin (); // create a new user $ model-> username = $ username; // complete the assignment $ model-> email = $ email; $ model-> password = $ password; // note that the setPassword method (magic _ set) in the Admin model is used if (! $ Model-> save () // save the new user {foreach ($ model-> getErrors () as $ error) // if the save fails, an error occurs, then the error message is output. {Foreach ($ error as $ e) {echo "$ e \ n" ;}} return 1; // The command line returns 1 indicating an exception} return 0; // return 0 to indicate that everything is OK }}

InitController. php

Then run the following command in the command line:

Yii init/admin

Enter the username and password as prompted to generate a data record. when we view this record, we find that the plaintext password we entered is encrypted, the creation time, update time, and update time are also automatically filled in if not specified. The former uses the _ set magic method, and the latter uses the "action" method ", for more information about Yii2.0, see Yii2.0. There is also a possibility that the Chinese garbled characters may be run in cmd under the window, and no good solution is found. However, you can try the software that runs linux commands in Cygwin windows, which is quite useful, if it is set to UTF-8, it will not be garbled, and gcc or anything can be used.

3. now we can log on to the frontend and backend based on the data in our database. However, since the session and other functions are shared, we still exit when exiting, and the frontend and backend need further operations: refer to this wiki.

Backend, in backend/config/main. php or main-local.php

'components' => ['user' => ['identityClass' => 'backend\models\Admin','enableAutoLogin' => true,'identityCookie' => ['name' => '_backendUser', // unique for backend],],'session' => ['name' => 'PHPBACKSESSID','savePath' => sys_get_temp_dir(),],'request' => ['cookieValidationKey' => 'orGkZNZvZe3-4WicYHyGMS-EyI6Tp8yi',//random string'csrfParam' => '_backendCSRF',],

Also at the front end, in frontend/config/main. php or main-local.php

'components' => ['user' => ['identityClass' => 'frontend\models\User','enableAutoLogin' => true,'identityCookie' => ['name' => '_frontendUser', // unique for frontend]],'session' => ['name' => 'PHPFRONTSESSID','savePath' => sys_get_temp_dir(),],'request' => ['cookieValidationKey' => '8rqO22WJ9yiAx_KuJ8SFnbKctqGDWi9J','csrfParam' => '_frontendCSRF',],

In this way, try again and you will find that the front and back ends are completely unrelated. You can call the Yii ::$ app function, for example, Yii ::$ app-> user-> id. if it is in the background directory, the user id in the background is displayed, if it is in the foreground directory, the foreground user ID is displayed. Some obsessive-compulsive disorder patients may want to use Yii: $ app-> admin-> id to access the background User id like Yii1. this is not a good implementation. compared with Yii2 and Yii1, user verification is a big change. The web/User is the core component in the Yii2 framework. if you want to modify it, you need to associate it with the variable methods in the web/Application. I don't feel necessary.

The above, is said, in fact there are many integrated yii2-user, with permission control and other plug-ins can be directly from the composer search for use. For example, if the CTR is the highest, type B verification can be configured and more functions are integrated.

Round (7), yii2migrate has been busy with other tasks recently (in fact, it is lazy !), I 've read Yii2 in depth, but it's a little clear at the beginning...

Related Article

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.