Yii Framework framework uses YIIC to quickly create migrate usage examples of YII applications _php instances

Source: Internet
Author: User
Tags createindex findone getting started with php smarty template
This example describes the migrate usage of the YII framework framework to quickly create YII applications using YIIC. Share to everyone for your reference, as follows:

Yii Migrate

View Help

/*/www/yii_dev/yii/framework# php yiic Migrate helperror:unknown action:helpusage YIIC migrate [action] [Parameter]desc Ription This command provides the support for database migrations. The optional ' action ' parameter specifies which specific migration task to perform. It can take these values:up, down, to, create, history, new, Mark. If the ' action ' parameter is not given, it defaults to ' up '. Each action takes different parameters. Their usage can be found in the following examples. examples* YIIC migrateapplies all new migrations. This was equivalent to ' YIIC migrate to '. * YIIC migrate Create create_user_tablecreates a new migration named ' Create_user_ Table '. * YIIC migrate up 3Applies the next 3 new migrations.* YIIC migrate downreverts the last applied migration.* YIIC m Igrate down 3Reverts The last 3 applied migrations.* YIIC migrate to 101129_185401migrates up or down to version 101129_18 5401.* YIIC Migrate Mark 101129_185401modifies The migration to version 101129_185401.no actual migration'll be performed.* YIIC migrate historyshows all previously applied migration information.* YIIC migrate 10Shows The last applied migrations.* YIIC migrate newshows all new migrations.* YIIC migrate new 10Shows the next migrations that has not been applied.*/

As we develop the process, the structure of the database is constantly tuned. In our development, we need to keep the code and database library in sync. Because our application is inseparable from the database. For example: in the development process, we often need to add a new table, or we later put into operation of the product, you may need to index a column. We have to keep the data structure and code consistent. If the code and the database are out of sync, the entire system may not function correctly. For this reason. YII provides a database migration tool to keep your code and database synchronized. facilitates rollback and update of databases.

function as described. Mainly provides the database migration function.

Command format

YIIC migrate [action] [parameter]

The action parameter is used to define which migration task to perform. Can be used as a

Up, down, to, create, history, new, mark. These commands

If there is no action parameter, the default is up

The parameter varies depending on the action.

The above example gives a description.

The official also gives a detailed example.

Http://www.yiiframework.com/doc/guide/1.1/zh_cn/database.migration#creating-migrations

There is no longer a detailed statement of exhaustion. When used, refer to the use of it.

Add: yii2.0 use migrate to create a background login

Re-create a data table to complete background login verification

For everyone to see clearly, the direct sticker code

I. Create a table with migration admin

Console\migrations\m130524_201442_init.php

Use Yii\db\schema;use yii\db\migration;class m130524_201442_init extends migration{const Tbl_name = ' {{%admin}} ';    Public Function Safeup () {$tableOptions = null; if ($this->db->drivername = = = ' MySQL ') {//Http://stackoverflow.com/questions/766809/whats-the-difference-bet    Ween-utf8-general-ci-and-utf8-unicode-ci $tableOptions = ' CHARACTER SET UTF8 COLLATE utf8_unicode_ci engine=innodb ';  } $this->createtable (Self::tbl_name, [' id ' = = schema::type_pk, ' username ' = = schema::type_string . ' Not NULL ', ' auth_key ' = schema::type_string. ' (+) not NULL ', ' password_hash ' = = schema::type_string. ' Not NULL ',//password ' password_reset_token ' = + schema::type_string, ' email ' + schema::type_string. ' Not NULL ', ' role ' = = Schema::type_smallint. ' Not NULL DEFAULT ten ', ' status ' = = Schema::type_smallint. ' Not NULL DEFAULT ', ' created_at ' and ' = Schema::type_integer. ' Not NULL ', ' updated_aT ' = Schema::type_integer.    ' Not NULL ',], $tableOptions);    $this->createindex (' username ', self::tbl_name, [' username '],true);  $this->createindex (' email ', self::tbl_name, [' email '],true);  } public Function Safedown () {$this->droptable (self::tbl_name); }}

Use the command line to create the admin database

1. Use the command under Win7:

Under Project root, right-click User Composer here (provided the global composer is installed),
Yii Migrate

That is to create the data table admin success

2, Linux under the same command (here slightly)

Ii. using the GII to create a model

Here a little, very simple step together.

Note: The admin model is created under Backend/models (where to see a person likes)
The code is as follows

namespace Backend\models;use yii;use yii\base\notsupportedexception;use yii\behaviors\timestampbehavior;use yii\db\ Activerecord;use yii\web\identityinterface;/** * This is the Model class for table "{{%admin}}". * * @property integer $id * @property string $username * @property string $auth _key * @property string $password _hash * @p Roperty string $password _reset_token * @property string $email * @property integer $role * @property integer $status * @pr Operty integer $created _at * @property integer $updated _at */class agadmin extends ActiveRecord implements Identityinterfa  ce{const status_deleted = 0;  Const STATUS_ACTIVE = 10;  Const ROLE_USER = 10;  Const Auth_key = ' 123456 ';  /** * @inheritdoc * */public static function TableName () {return ' {{%admin}} ';  }/** * @inheritdoc */Public Function behaviors () {return [Timestampbehavior::classname (),]; }/** * @inheritdoc * * * Public Function rules () {return [[' username ', ' email ',], ' required'], [[' username ', ' email '], ' string ', ' max ' = 255], [[' Username '], ' unique ', [[' Username '], ' match ', ' Pattern ' = '/^[a-z]\w*$/i '], [[' Email '], ' unique ', [[' Email '], ' email ', [' status ', ' Default ', ' value ' =  > self::status_active], [' STATUS ', ' in ', ' range ' = [self::status_active, self::status_deleted]], [' Role ', ' Default ', ' value ' = ' self::role_user], [' Auth_key ', ' Default ', ' value ' = = Self::auth_key], [' ROLE ', ' in '  , ' range ' = [self::role_user]]; }/** * @inheritdoc */public static function Findidentity ($id) {return Static::findone ([' id ' = = $id, ' Statu  s ' = = self::status_active]); }/** * @inheritdoc */public static function Findidentitybyaccesstoken ($token, $type = null) {return static::f    Indone ([' access_token ' = $token]);  throw new NotSupportedException (' Findidentitybyaccesstoken ' is not implemented. '); }/** * Finds user by Username * * @param string $usernaMe * @return Static|null */public static function Findbyusername ($username) {return static::findone ([' username '  = $username, ' status ' = Self::status_active]);   }/** * Finds user by password reset token * * @param string $token password reset token * @return Static|null */public static function Findbypasswordresettoken ($token) {if (!static::ispasswordresettokenvalid ($token)) {R    Eturn null;  } return Static::findone ([' Password_reset_token ' = $token, ' status ' = Self::status_active,]); }/** * Finds out if password reset token is valid * * @param string $token password reset token * @return Boolea    n */public static function Ispasswordresettokenvalid ($token) {if (empty ($token)) {return false;    } $expire = Yii:: $app->params[' User.passwordresettokenexpire ');    $parts = Explode (' _ ', $token);    $timestamp = (int) end ($parts);  return $timestamp + $expire >= time (); }/** * @inheritdOC */Public Function getId () {return $this->getprimarykey ();  }/** * @inheritdoc * * * Public Function Getauthkey () {return $this->auth_key;  }/** * @inheritdoc */Public Function Validateauthkey ($authKey) {return $this->getauthkey () = = = $authKey; }/** * Validates password * * @param string $password password to validate * @return Boolean if password provide D is valid for current user */Public Function ValidatePassword ($password) {return Yii:: $app->security->vali  Datepassword ($password, $this->password_hash); }/** * Generates password hash from password and sets it to the model * * @param string $password */Public fun Ction SetPassword ($password) {$this->password_hash = Yii:: $app->security->generatepasswordhash ($password)  ; }/** * generates "Remember Me" authentication key */Public Function Generateauthkey () {$this->auth_key = Y  II:: $app->security->generaterandomstring ();}/** * Generates new password reset token */Public Function Generatepasswordresettoken () {$this->password_ Reset_token = Yii:: $app->security->generaterandomstring (). '_' .  Time (); }/** * Removes password reset token */Public Function Removepasswordresettoken () {$this->password_reset_to  Ken = null; }}

Third, the use of migrate for the back of a login account

1, console\controllers Create initcontroller.php

/** * * @author Chan 
  
    */namespace console\controllers;use back End\models\admin, class Initcontroller extends \yii\console\controller{/** * Create init user */Public function AC         Tionadmin () {echo "Create a new user ... \ n";    Prompt for current operation $username = $this->prompt (' User Name: ');        Receive username $email = $this->prompt (' email: ');     Receive email $password = $this->prompt (' Password: ');              Receive password $model = new Agadmin ();          Create a new user $model->username = $username;    Completion assignment $model->email = $email;    $model->password = $password; if (! $model->save ())//Save new User {foreach ($model->geterrors () as $error)//If the save fails, indicating an error, then output      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}} 
   

2. Use the command:

Under Project root, right-click User Composer here (provided the global composer is installed),
Yii Init/admin

In this case, open the data table to see that the data is already available.

Four, backstage login verification

1, backend\controllers\sitecontroller.php Actionlogin method does not change

2, the common\models\loginform.php copy to Backend\models as long as the loginform.php inside the method GetUser () modify a word can, as follows

Public Function GetUser () {    if ($this->_user = = = False) {      $this->_user = Admin::findbyusername ($this username);    }    return $this->_user;}

3, backend\config\main.php as long as modify

' User ' = [  ' identityclass ' = ' backend\models\admin ',  ' enableautologin ' = true,],

In addition, when making changes, please note that the command empty don't mess up.

To this end.

For more information on YII related content readers can view this site topic: "YII framework Introduction and common skills Summary", "PHP Excellent Development Framework Summary", "Smarty Template Primer Basic Tutorial", "PHP date and Time usage summary", "PHP object-oriented Programming introduction Tutorial", " PHP String Usage Summary, "Getting Started with Php+mysql database operations" and "PHP Common Database Operations Skills Summary"

It is hoped that this article is helpful to the PHP program design based on YII framework.

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