The YII framework framework uses YIIC to quickly create migrate usages of yii application _php Example

Source: Internet
Author: User
Tags auth createindex findone reset smarty template yii

This example describes the migrate usage of the YII framework framework to quickly create YII applications using YIIC. Share to everyone for your reference, specific as follows:

Yii Migrate

View Help

/*/www/yii_dev/yii/framework# PHP YIIC migrate help Error:unknown action:help USAGE YIIC Migrate [action] [parameter] DESCRIPTION This command provides support the for database migrations.
 The optional ' action ' parameter specifies which specific task to migration.
 It can take these values:up, down, to, create, history, new, Mark.
 If the ' action ' parameter is isn't given, it defaults to ' up '. Each action takes different parameters.

Their usage can be found in the following examples. Examples * YIIC migrate applies all new migrations.
This is equivalent to ' YIIC migrate to '.
* YIIC Migrate Create create_user_table creates a new migration named ' Create_user_table '.
* YIIC Migrate up 3 applies the next 3 new migrations.
* YIIC migrate down reverts applied migration.
* YIIC migrate down 3 reverts of the last 3 applied migrations.
* YIIC migrate to 101129_185401 migrates up or down to version 101129_185401. * YIIC Migrate Mark 101129_185401 modifies migration historY up or down to version 101129_185401.
No actual migration would be performed.
* YIIC Migrate history shows all previously applied migration.
* YIIC Migrate history shows the last applied migrations.
* YIIC Migrate new shows all new migrations.
* YIIC Migrate new shows the next migrations that have not been applied.

 */

In the process of developing the program, the structure of the database is also constantly adjusted. In our development, we need to keep our code and database libraries synchronized. Because our application is inseparable from the database. For example, during the development process, we often need to add a new table, or a product that we later put into operation, may need to index a column. We must keep the data structure and code consistent. If the code and database are not synchronized, the entire system may not function correctly. For this reason. YII provides a database migration tool that keeps code and databases synchronized. Facilitate database rollback and update.

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 argument, the default is up

Parameter varies depending on the action.

A description is given in the above example.

The authorities also gave a detailed example.

Http://www.yiiframework.com/doc/guide/1.1/zh_cn/database.migration

This is no longer described in detail. When you use the reference to use it.

Add: yii2.0 use migrate to create background login

Recreate a data table to complete background login verification

For everyone to see clearly, the direct labeling code

First, use migration to create TABLE 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 '; } $this->createtable (Self::tbl_name, [' ID ' => schema::type_pk, ' username ' => schema::type_s TRING. ' 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 ', ' status ' => schema::type_smallint. ' Not NULL DEFAULT ', ' created_at ' => schema::type_integer. ' NotNULL ', ' updated_at ' => schema::type_integer.
    ' Not NULL ',], $tableOptions);
    $this->createindex (' username ', self::tbl_name, [' username '],true);
  $this->createindex (' email ', self::tbl_name, [' email '],true);
  The Public Function Safedown () {$this->droptable (self::tbl_name);

 }
}

To create the admin database by using the command line

1, Win7 under the use of the command:

At the root of the project, right-click the user composer here (provided the global composer is installed),
Yii Migrate

That is, create the data table Admin succeeded

2, Linux under the same command (here slightly)

Using GII to create a model

Here is a brief, simple step together.

Note: The admin model is created under Backend/models (where to see a person's 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 are 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 $stat US * @property integer $created _at * @property integer $updated _at */class Agadmin extends ActiveRecord implements Ide
  ntityinterface {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], [[' Us Ername '], ' unique ', [[' Username '], ' match ', ' pattern ' => '/^[a-z]\w*$/i '], [[' Email '], ' unique '], [[' E Mail '], ' email ', [' status ', ' Default ', ' Value ' => self::status_active], [' status ', ' in ', ' range ' => [se Lf::status_active, self::status_deleted]], [' Role ', ' Default ', ' Value ' => self::role_user], [' Auth_key ', ' d
  Efault ', ' 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 STA
    Tic::findone ([' Access_token ' => $token]); throw new NotSupportedException (' Findidentitybyaccesstoken ' is not implemented. '); }/** * finds user by username * * @param string $username * @return static|null/public static funct Ion Findbyusername ($username) {return static::findone ([' username ' => $username, ' status ' => self::status_acti
  VE]); /** * finds user by password reset token * * @param string $token password reset token * @return Static|nu  ll/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 b
    Oolean/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 () = = = $auth
  Key; }/** * Validates password * * @param string $password password to validate * @return Boolean if password PR Ovided is valid to 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/Publ IC function SetPassword ($password) {$this->password_hash = Yii:: $app->security->generatepasswordhash ($pass
  Word); }/** * GeNerates "Remember Me" authentication key */Public Function Generateauthkey () {$this->auth_key = Yii:: $app-
  >security->generaterandomstring (); }/** * Generates new password reset token/public Function Generatepasswordresettoken () {$this->pas Sword_reset_token = Yii:: $app->security->generaterandomstring (). '_' .
  Time (); }/** * Removes password reset token/public Function Removepasswordresettoken () {$this->password_re
  Set_token = null;

 }
}

Third, the use of migrate for the last to make a landing account

1, console\controllers Create initcontroller.php

/** * @author Chan <maclechan@qq.com> * * namespace console\controllers; use Backend\mo
Dels\admin;
  Class Initcontroller extends \yii\console\controller {/** * Create init user */Public Function actionadmin ()         {echo "Creates a new user ... \ n";    Prompts the current action $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 of assignment $model->email = $email;
    $model->password = $password; if (! $model->save ())//Save new User {foreach ($model->geterrors () as $error)////If Save fails with error, then
      Output error message.
        {foreach ($error as $e) {echo "$e \ n";                  } return 1;                    The command line returns 1 to indicate an exception} return 0; Returns 0 representing all OK}} 

2, the use of the command:

At the root of the project, right-click the user composer here (provided the global composer is installed),
Yii Init/admin

To this, open the data table look, already have the data.

Four, background 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 modified

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

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

To this, the end.

More about Yii related content readers can view the site topics: "Yii framework Introduction and common skills Summary", "PHP Excellent Development Framework Summary", "Smarty Template Primer Tutorial", "PHP date and Time usage summary", "PHP object-oriented Programming Program", " Summary of PHP string usage, Introduction to PHP+MYSQL database operations, and a summary of PHP common database operations Tips

I hope this article will help you with the PHP program design based on the 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.