Separation and migrate use of Yii2 before and after stage (vii) _php example

Source: Internet
Author: User
Tags php foreach yii

have been busy with other recently (actually is lazy!) ), read "Yii2", some did not understand a little more clearly point, and then see yii2 image upload processing, rich text, restful what, but because did not go here, only to see also no use Ah, so or follow the steps to step, first said before and after the Taiwan separation. (In fact, the common content management site does not need to say the following completely separate what, see also no harm)

Personal feeling before and after the Taiwan situation there are so many, the first is whether the front and back of the platform is a verification system, followed by whether or not to share a data table.

In general, the following three kinds of more commonly used bar:

A, sharing a validation system and a data table.

B, two validation systems and a shared data table.

C, two validation systems and two data tables.

Yii2 Advanced version of the default is a type, that is, the same data table, and one side login/log out, the other side also log on/log out, feel this structure is more suitable for the forum this, the Administrator also needs to have the same as Members post replies and other Functions, table field is also basically consistent, (personally think that, after all, contact not much, The Internet also searched different background to build the topic, but there are few detailed discussion, this can be through the fields, permissions, etc. to distinguish the front and back. And we are going to do is type C, such as some of the electrical business site, backstage administrator and the front desk member function is too big, and the table field difference is also large, so the verification system is not the same, and put two data table better. As for Type B is a C-type simplified version, c if it is set, B also the same.

So let's build an admin table to hold the admin data, and the members still use the original user table, which is created using Yii's migrate, as mentioned in the YII2 initialization section, and here's a little detail:

1, YII2 version 2.07 before using the command, you can create a PHP file in the Console/migrations directory, and then write the creation table under this file statement, 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 missing a status field, then I can directly use the following command will generate only add fields of files

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

Generated:

<?php use
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 of the Actioncreate method:

} 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 match add_xxx_to_xxx to determine which template to point to, resulting in different styles.

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

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

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

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 from 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 appropriate for their actions, you can do this:

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

return [
///Modify Migration template
' Controllermap ' => [
' Migrate ' => [
' class ' => '] yii\console\ Controllers\migratecontroller ',
' templatefile ' => ' @yii/views/migration.php ',//default template, 2.07 should be rarely used
' Generatortemplatefiles ' => [
' create_table ' => ' @console/views/createtablemigration.php ',//modified
' drop _table ' => ' @yii/views/droptablemigration.php ',//unmodified
' add_column ' => ' @console/views/ Addcolumnmigration.php ',//modified '
drop_column ' => ' @console/views/dropcolumnmigration.php ',//Modified
' Create_junction ' => ' @yii/views/createjunctionmigration.php '//unmodified],
],

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 in the vendor/yiisoft/yii2/console/ migratecontroller.php, or you use the not write the command template will be an error.

As for how to write specific creation tables, add fields and other statements, in fact, there are versions of the different (2.06 new writing) Two ways to write, here is not to see the Chinese version of the Yii2 guide, directly to see the English update, point here, which contains the above mentioned content and the specific wording. It took a lot of time to search Google, follow the source to understand the above said the principle, then a look, in the people's English version of the written, tragedy, and recently I in Yii English official website API document Search Any keyword does not appear results, do not know is this side of the problem or official website problem, You can only compare the Chinese and English guides to see which one is the corresponding. So if English is better, read the English document directly.

At present, I modified the create_table when adding table comments, paragraph comments (this search and check source did not find a similar->comment, may be to compatible with other databases, so can only stitching, and write a paragraph annotation benefits are, 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 an example annotation to make it easier to write in reference to the annotation when forgetting the usage. And then you don't have to add--fileds parameters. Well, here's your template and the admin table you should end up with:

Template createtablemigration.php:

<?php/** * This view was 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 $f
Ields array The fields */echo "<?php\n";?> use yii\db\migration; Class <?= $className?> extends Migration {Const Tbl_name = ' {{%<?= $table '} '; public function up () {$table
Options = null; if ($this->db->drivername = = ' MySQL ') {$tableOptions = ' CHARACTER SET UTF8 COLLATE utf8_general_ci engine=innodb C
Omment= "Fill in form Notes"; $this->createtable (Self::tbl_name, [<?php foreach ($fields as $field):?> <?php if ($field = = End ($fields)) :?> ' <?= $field [' property ']?> ' => $this-><?= $field [' decorators ']. \ "COMMENT ' fills in the section annotation '" ". "\ n"?> <?php else:?> ' <?= $field [' property ']?> ' => $this-><?= $field [' decorators ']. " \ "COMMENT ' fills in the section annotation '" ". ", \ n"?> <?php endif;?> <? PHP Endforeach?>], $tableOptions); Public function down () {$this->droptable (self::tbl_name);}}

Concrete Statement m160326_133655_create_admin.php:

<?php use 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 C
omment= "Backstage Administrator table"; $this->createtable (Self::tbl_name, [' id ' => $this->primarykey (), ' username ' => $this->string ()-> Notnull ()->unique (). " COMMENT ' username ', ' auth_key ' => $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 ' mailbox ', ' status ' => $this->smallinteger ()->notnull ()->defaultvalue (10). " COMMENT ' state ', ' 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's just a demo, so admin and user tables are basically the same, don't care about these details.

Yii Migrate

Well, after generating two tables, we need to completely separate the front and back login:

1, the front changes: because it is no longer common, so the common common/models in the user.php and loginform.php moved to Frontend/models, by the way, the namespace of the two files to the frontend to start, Look through the entire foreground file and change all the requirements that pertain to the two common file namespaces to the foreground's own namespace.

2, Background modification: the same need in backend/ There are two files admin.php and loginform.php in the models that you can use in GII (note that you want to inherit identityinterface, implement the methods within this interface, and refer to user.php to implement the relevant login registration method), or you can copy the same two text directly above (You need to rename user.php to admin.php, and note that the user table and Admin table field names or numbers are consistent, and that inconsistencies need to be modified in admin.php). Since we originally created Grud in the background, there are a lot of changes here (Searchmodel,controller,view need to be admin), and we recommend that you change the preview of the files that are generated in the GII. Hey, if you actually want to separate back and forth, this chapter should be placed in front of the fifth chapter, then the background does not need to change so much.

Now you can login to the front and rear table to try, and so on, our backstage table although created well, but has not added the administrator, now because the backstage has not entered the landing, so in the background can not be created, and the registration function is not (this separation, the background generally does not need to have the registration function), So here continue to use the function of console to create a user, the console functions quite a lot, not only database management, you can click here to understand.

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

<?php
/**
* Application Initialization
* Refer to the 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";//Hint current action
$username = $this->prompt (' admin Name: '); Receive username
$email = $this->prompt (' email: ');//Receive email
$password = $this->prompt (' Password: ');//Receive Password c18/> $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 (Magic Method __set) in the admin model
if (! $model->save ())//Save new user
{
foreach ($model->geterrors () as $error)//If the save fails, indicating an error, the error message is printed.
{
foreach ($error as $e)
{
echo "$e \ n";
}
}
return 1; The command line returns 1 to indicate an exception
} return
0;//returns 0 means all OK
}

initcontroller.php

And then run on the command line:

Yii Init/admin

Follow the prompts to fill in the username password and so on, you can produce a piece of data, when we look at this record, we found that the plaintext password we filled out becomes encrypted, and we have not filled in the creation time and update and update time, the former is due to use the __set magic method, the latter is used "behavior", If not very understanding, please see "deep understanding Yii2.0", which is more detailed. There is, may be in the window under CMD run Chinese garbled, generally search the next did not find a good solution, but you can try to 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 according to their own database data to log in, but due to the session and other common one, so or exit, before and after the exit together, need further action: you can refer to this wiki.

Backstage, 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 desk, 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 ',
],

This landing test, you will find that the front and back of the table is completely unrelated. You can invoke Yii:: $app features such as Yii:: $app->user->id, in the background of the directory, will display the background of the user ID, if it is in the foreground of the directory will display the foreground of the user ID. Maybe some OCD patients want to use yii like YII1:: $app->admin->id to access the background user ID, this is not a 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 web/application in the variable method, etc., personal feeling is not necessary.

Above, is said, in fact, there are many integrated yii2-user, with access control and other plug-ins can be directly from the composer search for use. For example, this is the highest rate of hits, you can configure Type B authentication, and integrate more features.

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.