YIIFramework framework uses YIIC to quickly create a migrate usage instance for YII applications. yiicyii_PHP tutorial

Source: Internet
Author: User
Tags createindex findone
The YIIFramework framework uses YIIC to quickly create the migrate usage instance of the YII application, and yiicyii. The YIIFramework framework uses YIIC to quickly create the migrate usage instance of the YII application. yiicyii this article describes how the YIIFramework framework uses YIIC to quickly create a YII application using migrate. Describes how to quickly create a migrate usage instance for a YII application using YIIC in the YII Framework.

This article describes how to use the YII Framework to quickly create a YII application using YIIC. We will share this with you for your reference. The details are as follows:

Yii migrate

View Help

/*/www/yii_dev/yii/framework# php yiic migrate helpError: Unknown action: helpUSAGE yiic migrate [action] [parameter]DESCRIPTION This command provides 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 is 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 migrate down 3Reverts the last 3 applied migrations.* yiic migrate to 101129_185401Migrates up or down to version 101129_185401.* yiic migrate mark 101129_185401Modifies the migration history up or down to version 101129_185401.No actual migration will be performed.* yiic migrate historyShows all previously applied migration information.* yiic migrate history 10Shows the last 10 applied migrations.* yiic migrate newShows all new migrations.* yiic migrate new 10Shows the next 10 migrations that have not been applied.*/

During our program development, the database structure is constantly adjusted. In our development, we must ensure the synchronization of code and database. Because our applications cannot be separated from databases. For example, during the development process, we often need to add a new table or a product that we put into operation later, we may need to add an index for a column. We must maintain data structure and code consistency. If the code and database are not synchronized, the entire system may fail to run normally. For this reason. Yii provides a database migration tool to keep the code and database synchronized. This facilitates database rollback and updates.

The function is described as follows. Mainly provides the database migration function.

Command format

Yiic migrate [action] [parameter]

The action parameter is used to determine which migration task to execute. Available for use

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

If no action parameter exists, the default value is up.

Parameter varies according to the action.

The above example shows the description.

The official team also provides detailed examples.

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

I will not go into detail here. You can use it for reference.

Supplement: yii2.0 uses migrate to create background login

Create a new data table to complete background login verification

Directly paste the code for your understanding

1. use Migration to create the admin table

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-between-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. '(32) 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 10', 'status' => Schema: TYPE_SMALLINT. 'Not null default 10', 'created _ at' => 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 an admin database

1. run the following command in win7:

Right-click the Project root directory and select User composer here (provided that the global composer is installed ),
Yii migrate

The data table admin is created successfully.

2. linux commands are the same (omitted here)

II. use gii to create a model

This is a simple step.

Note: create the admin model under backend/models (where to look at your preferences)
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 * @property string $password_reset_token * @property string $email * @property integer $role * @property integer $status * @property integer $created_at * @property integer $updated_at */class AgAdmin extends ActiveRecord implements IdentityInterface{  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, 'status' => self::STATUS_ACTIVE]);  }  /**   * @inheritdoc   */  public static function findIdentityByAccessToken($token, $type = null)  {    return static::findOne(['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)) {      return 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 boolean   */  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 provided is valid for current user   */  public function validatePassword($password)  {    return Yii::$app->security->validatePassword($password, $this->password_hash);  }  /**   * Generates password hash from password and sets it to the model   *   * @param string $password   */  public function setPassword($password)  {    $this->password_hash = Yii::$app->security->generatePasswordHash($password);  }  /**   * Generates "remember me" authentication key   */  public function generateAuthKey()  {    $this->auth_key = Yii::$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_token = null;  }}

3. use migrate as a logon account.

1. console \ controllers creates InitController. php

/***** @ Author chan
 
  
*/Namespace console \ controllers; use backend \ models \ Admin; class InitController extends \ yii \ console \ Controller {/*** Create init user */public function actionAdmin () {echo "creates a new user... \ n "; // the system prompts the current operation $ username = $ this-> prompt ('user Name :'); // receiving username $ email = $ this-> prompt ('email: '); // receiving Email $ password = $ this-> prompt ('password :'); // receive password $ model = new AgAdmin (); // create a new user $ model-> username = $ u Sername; // complete the assignment $ model-> email = $ email; $ model-> password = $ password; 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 }}
 

2. run the following command:

Right-click the Project root directory and select User composer here (provided that the global composer is installed ),
Yii init/admin

At this point, open the data table and check that the data already exists.

IV. background login verification

1. do not change the actionLogin method in backend \ controllers \ SiteController. php

2. copy common \ models \ LoginForm. php to backend \ models and modify the method getUser () in LoginForm. php as follows:

public function getUser(){    if ($this->_user === false) {      $this->_user = Admin::findByUsername($this->username);    }    return $this->_user;}

3. modify backend \ config \ main. php

'user' => [  'identityClass' => 'backend\models\Admin',  'enableAutoLogin' => true,],

In addition, when making changes, please note that do not mess up the command empty.

This ends.

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.