YII2 Separation and migrate use (vii) _php example

Source: Internet
Author: User
Tags php foreach utf 8
have been busy all the time lately (actually lazy!) ), will be "in-depth understanding Yii2" looked again, some did not understand a little clear point, and then see yii2 image upload and other processing, rich text, restful what, but because did not go here, only see also no matter use Ah, so still follow step by step, first said before and after the Taiwan separation. (In fact, the normal content management site does not need to say that the complete separation of what, see also no harm)

Personal feelings before and after the situation there are so many, the first is whether the front and rear platform is a verification system, followed by whether the front and back table is a common data sheet.

Generally, the following three kinds of comparison are commonly used:

A, a common authentication system and a data table.

B, two authentication systems and a single data table.

C, two verification systems and two datasheets.

YII2 Premium version of the default is a type, that is, the same data table, and one side login/logout, the other side also log on/log out, feel that this structure is applicable to the forum this, the Administrator also need to have the same as the Member Post replies and other functions, table fields are basically consistent, (individuals think, after all, not much contact The web has also searched for different background-building topics, but few are discussed in detail, which can be distinguished by fields, permissions, and so forth. And we are going to do is C type, like some e-commerce website, backstage Administrator and front desk member function is too big, and table field difference is also big, so the verification system is not the same, and put two data table is better. As for Type B is a simplified version of C, if C is set, B will do the same.

Then we first set up an admin table to hold the administrator data, and members still use the original user table, here with Yii migrate to create, in the YII2 initialization section mentioned, here a little more detailed:

1, YII2 version 2.07 before using the command, you can create a php file under the Console/migrations directory, and then write the creation of table statements and so on.

Yii migrate/create Admin

2, YII2 version 2.07, added a more detailed classification, for example, I have created the admin table, but a status field is missing, I can directly use the following command will be generated only add the field of the file

Yii migrate/create add_column_to_admin--fields=status:int (Ten): Nontnull

Generated:

<?phpuse yii\db\migration;class M160501_053640_add_column_to_admin extends Migration{public function up () {$this- >addcolumn (' admin ', ' status ', $this->int ()->nontnull ());} Public function down () {$this->dropcolumn (' admin ', ' status ');}}

Specifically why this, we look at the original code, in the vendor/yiisoft/yii2/console/basemigratecontroller.php file in the Actioncreate method:

} elseif (Preg_match ('/^add_ (. +) _to_ (. +) $/', $name, $matches)) {$content = $this->renderfile (Yii::getalias ($this- >generatortemplatefiles[' Add_column '), [' className ' = $className, ' table ' and ' Mb_strtolower ' ($matches [2], Yii:: $app->charset), ' fields ' = $this->fields]);}

As we can see, here is a regular match add_xxx_to_xxx to determine exactly which template to point to, thus creating a different style.

A total of these styles are matched according to the parameters following migrate/create:

1, create_junction_ table name _and_ table name, used to create the junction table

2, add_xxx_to_ table name, used to add the field (you can use the--fields style to specify a field, otherwise generate empty, you need to write yourself, of course, you can also change the template to add a comment example)

3, DROP_XXX_FROM_ table name, used to delete the field (IBID.)

4, Create_ table name, used to create the table

5, DROP_ table name, used to delete the table

Note: You can use Yii help migrate directly in the console to see more usage

Template files can be found in the vendor/yiisoft/yii2/views, if you want to change the template to make it more suitable for your operation, you can:

Create a new Views folder in the console file, copy the template you want to modify here to modify it, and then modify it in console/config/main.php.

It is noteworthy that the Generatortemplatefiles configuration, the 5 must be written all, if not modified, then write the original path, the original path can be vendor/yiisoft/yii2/console/ migratecontroller.php, otherwise you will get an error when you use the command template that you did not write.

As to how to write specific tables, add fields and other statements, in fact there are different versions (2.06 new wording) of the two kinds of writing, here do not look at the Chinese version of the Yii2 Guide is not updated, directly to the English update, point here, which contains the above said content plus specific wording. Originally took a lot of time Google search, follow the source to understand the above said the principle, then a look, in others English version is written, tragedy, and recently I in Yii English official website API document search any key words do not appear results, do not know is this side of the problem or official website problem, It can only be compared to the Chinese guide and English Guide to see exactly which piece corresponds. So if the English is better, read the English document directly.

At present, I modified the create_table annotated, paragraph comments (this search and the source did not find a similar->comment, it may be to be compatible with other databases, so only splicing, and the benefit of writing paragraph notes, the GII When the model is generated, the Attributelabels method can display the corresponding Chinese name directly according to the annotation, and the Add_column and Drop_column templates add a sample comment, which makes it easy to forget the example of the annotation when using it. And so you don't have to add--fileds parameters. Well, here's a statement of your template and the admin table that should be created:

Template createtablemigration.php:

<?php/*** This view was used by console/controllers/migratecontroller.php* the following variables was available in this view:*//* @var $className String The new migration class name *//* @var $table string The name table *//* @var $fields ar Ray 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 UTF 8 COLLATE utf8_general_ci engine=innodb comment= "Fill in the Table notes";} $this->createtable (Self::tbl_name, [<?php foreach ($fields as $field):? ><?php if ($field = = End ($fields)):? > ' <?= $field [' property ']?> ' = ' and $this-><?= $field [' decorators ']. \ "COMMENT" fills in the paragraph comment ' \ '. "\ n"? ><?php else:?> ' <?= $field [' property ']?> ' = ' and $this-><?= $field [' decorators ']. \ "COMMENT" fills in the paragraph 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}} ';p ublic function up () {$tableOptions = null;if ($this->db->drivername = = = ' MySQL ') {$tableOptions = ' CHARACTER SET UTF8 COLLA TE utf8_general_ci engine=innodb comment= "backstage Administrator table";} $this->createtable (Self::tbl_name, [' id ' = = $this->primarykey (), ' username ' + $this->string () Notnull ()->unique (). " COMMENT ' username ', ' auth_key ' and ' = ' $this->string (+)->notnull (). " COMMENT ' certified key ' ", ' password_hash ' + $this->string ()->notnull ()." COMMENT ' password ', ' password_reset_token ' + $this->string ()->unique (). " COMMENT ' password reset token ', ' email ' = ' $this->string ()->notnull ()->unique (). " COMMENT ' e-mail ', ' status ' = $this->smallinteger ()->notnull ()->defaultvalue (10). " COMMENT ' state ', ' created_at ' = '->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, you can generate the admin table, because just do the demo, so the admin and user table basically, do not care about these details.

Yii Migrate

OK, after generating two tables, we need to completely separate the foreground login and background login:

1, the foreground modification: because already is not common, so first the common common/models in the user.php and loginform.php moved to Frontend/models, by the way, the two files of the namespace changed to start with Frontend, Look through the entire foreground file and change all of the two common file namespaces to the foreground namespace.

2, the background modification: also need in backend/ There are two files in models, admin.php and loginform.php, which can be generated using the GII (note the need to inherit identityinterface, implement methods within this interface, and refer to user.php to implement the relevant login registration method), or copy the same two (You need to rename user.php to admin.php, and note that the user and Admin table fields have a consistent name or number, and inconsistencies need to be modified in admin.php). Because we have created the background of the Grud, so there are a lot of changes (Searchmodel,controller,view need to change to admin), we recommend to the GII generated by the file preview to change. Alas, if the actual need to separate the front and back, this chapter should be placed in front of the fifth chapter, the backstage does not need to change so much.

can now log in front and back to try, and so on, our backstage table although created, but have not added the administrator, now because the background has not been logged in, so in the background can not be created, and the registration function is not (this separation, the background is generally not necessary to have registration function), So here continue to use the function of the console to create a user, the function of the console is very much, not just database management, you can click here to understand the next.

Create a new Initcontroller in Console/controllers and then the following code:

<?php/*** application initialization* refer to In-depth understanding Yii2.0 Video Tutorials */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 current operation $username = $this->prompt (' Admin Name: '); Receive User name:->prompt (' email £ º ') $this Receive Email$password = $this->prompt (' Password: '); Receive password $model = new Admin (); Create a new user $model->username = $username; Complete assignment $model->email = $email; $model->password = $password;//Note this place, using the SetPassword method in the admin model (Magic method __set) if (!$ Model->save ())//Save the new user {foreach ($model->geterrors () as $error)//If the save fails, indicating an error, then output the error message. {foreach ($error as $e) {echo "$e \ n";}} return 1; The command line returns 1 indicating an exception}return 0; Returns 0 means everything OK}}

initcontroller.php

Then run the command line:

Yii Init/admin

Follow the prompts to fill in the user name password, and so on, you can produce a data, when we look at this record, found that we fill in the plaintext password has become encrypted, and the creation time and update and update time we did not fill out also automatically to fill out, the former is due to use the __set magic method, the latter is used "behavior", If not very understanding please see "in-depth understanding of Yii2.0", which is more detailed. There is, may be in the window cmd run Chinese garbled, the general search did not find a good solution, but can try Cygwin this Windows can run Linux command software, very useful, set into utf-8 will not garbled, and can use GCC or something.

3, now we can follow the data in their own database to log in, but because of the session and other public one, so or exit, the back and forth together exit, need further operation: You can refer to this wiki.

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

' components ' + = [' user ' = ' = ' identityclass ' + ' backend\models\admin ', ' enableautologin ' and ' = True ' Identitycookie ' + ' = [' name ' = ' _backenduser ',//unique for backend], ' session ' = [' name ' = ' Phpbacksessid ' , ' savepath ' = Sys_get_temp_dir (),], ' request ' = = [' Cookievalidationkey ' and ' = ' Orgkznzvze3-4wicyhygms-eyi6tp8yi ',//random string ' csrfparam ' = ' _backendcsrf ',],

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

' components ' + = [' user ' = ' = ' identityclass ' + ' frontend\models\user ', ' enableautologin ' and ' = True ' Identitycookie ' + ' = [' name ' = ' _frontenduser ',//unique for frontend]], ' session ' = = [' Name ' = ' + ' Phpfrontsessi D ', ' Savepath ' + Sys_get_temp_dir (),], ' request ' = = [' Cookievalidationkey ' and ' = ' 8rqo22wj9yiax_ Kuj8sfnbkctqgdwi9j ', ' csrfparam ' = ' _frontendcsrf ',],

If you try again, you will find that the front and rear stations are completely unrelated. Can call Yii:: $app functions, such as Yii: $app->user->id, if it is in the background directory, the background user ID will be displayed, if it is in the foreground directory, the foreground user ID will be displayed. Maybe some obsessive-compulsive patients want to work with YII1. Yii:: $app->admin->id to access the background user ID, this is not very good implementation, YII2 and YII1 compared to the user to verify that the change is very large, web/user in the YII2 framework as the core components, If you want to modify the words should also be related to modify the variables in the Web/application method, etc., the personal feeling is not necessary.

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 use. For example, the highest clickthrough rate can be configured with type B validation, and more features are integrated.

  • 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.