欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

YII Framework框架使用YIIC快速創(chuàng)建YII應用之migrate用法實例詳解

 更新時間:2016年03月15日 09:37:41   作者:眼鏡群  
這篇文章主要介紹了YII Framework框架使用YIIC快速創(chuàng)建YII應用之migrate用法,詳細分析了migrate的功能與用法,并給出創(chuàng)建登錄后臺的實例講述了migrate的相關使用技巧,需要的朋友可以參考下

本文實例講述了YII Framework框架使用YIIC快速創(chuàng)建YII應用之migrate用法。分享給大家供大家參考,具體如下:

yii migrate

查看幫助

/*
/www/yii_dev/yii/framework# php yiic migrate help
Error: Unknown action: help
USAGE
 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 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 the last applied migration.
* yiic migrate down 3
Reverts the last 3 applied migrations.
* yiic migrate to 101129_185401
Migrates up or down to version 101129_185401.
* yiic migrate mark 101129_185401
Modifies the migration history up or down to version 101129_185401.
No actual migration will be performed.
* yiic migrate history
Shows all previously applied migration information.
* yiic migrate history 10
Shows the last 10 applied migrations.
* yiic migrate new
Shows all new migrations.
* yiic migrate new 10
Shows the next 10 migrations that have not been applied.
*/

在我們開發(fā)程序的過程中,數(shù)據(jù)庫的結(jié)構(gòu)也是不斷調(diào)整的。我們的開發(fā)中要保證代碼和數(shù)據(jù)庫庫的同步。因為我們的應用離不開數(shù)據(jù)庫。例如: 在開發(fā)過程中,我們經(jīng)常需要增加一個新的表,或者我們后期投入運營的產(chǎn)品,可能需要為某一列添加索引。我們必須保持數(shù)據(jù)結(jié)構(gòu)和代碼的一致性。如果代碼和數(shù)據(jù)庫不同步,可能整個系統(tǒng)將無法正常運行。出于這個原因。yii提供了一個數(shù)據(jù)庫遷移工具,可以保持代碼和數(shù)據(jù)庫是同步。方便數(shù)據(jù)庫的回滾和更新。

功能正如描述。主要提供了數(shù)據(jù)庫遷移功能。

命令格式

yiic migrate [action] [parameter]

action參數(shù)用來制定執(zhí)行哪一個遷移任務??梢砸皇褂?/p>

up, down, to, create, history, new, mark.這些命令

如果沒有action參數(shù),默認為up

parameter根據(jù)action的不同而有所變化。

上述例子中給出了說明。

官方也給出了詳細的例子。

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

這里不再詳細累述。用到的時候參考使用就可以了。

補充:yii2.0使用migrate創(chuàng)建后臺登陸

重新創(chuàng)建一張數(shù)據(jù)表來完成后臺登陸驗證

為了大家看得明白,直接貼代碼

一、使用Migration創(chuàng)建表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-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_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);
  }
}

使用命令行來創(chuàng)建admin數(shù)據(jù)庫

1、win7下使用命令:

在項目根目下,右鍵選擇User composer here(前提是安裝了全局的composer),
yii migrate

即創(chuàng)建數(shù)據(jù)表 admin成功

2、linux下命令一樣(此處略)

二、使用gii創(chuàng)建模型

此處略,很簡單的步聚。

注:把admin模型創(chuàng)在 backend/models下面 (放哪里看個人喜好)
代碼如下

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;
  }
}

三、使用migrate 為后如初使化一個登陸帳號

1、console\controllers創(chuàng)建InitController.php

/**
 *
 * @author chan <maclechan@qq.com>
 */
namespace console\controllers;
use backend\models\Admin ;
class InitController extends \yii\console\Controller
{
  /**
   * Create init user
   */
  public function actionAdmin()
  {
    echo "創(chuàng)建一個新用戶 ...\n";         // 提示當前操作
    $username = $this->prompt('User Name:');    // 接收用戶名
    $email = $this->prompt('Email:');        // 接收Email
    $password = $this->prompt('Password:');     // 接收密碼
    $model = new AgAdmin();              // 創(chuàng)建一個新用戶
    $model->username = $username;          // 完成賦值
    $model->email = $email;
    $model->password = $password;
    if (!$model->save())              // 保存新的用戶
    {
      foreach ($model->getErrors() as $error)   // 如果保存失敗,說明有錯誤,那就輸出錯誤信息。
      {
        foreach ($error as $e)
        {
          echo "$e\n";
        }
      }
      return 1;                  // 命令行返回1表示有異常
    }
    return 0;                    // 返回0表示一切OK
  }
}

2、使用命令:

在項目根目下,右鍵選擇User composer here(前提是安裝了全局的composer),
yii init/admin

到此,打開數(shù)據(jù)表看下,己經(jīng)有了數(shù)據(jù)。

四、后臺登陸驗證

1、backend\controllers\SiteController.php 里actionLogin方法不用變

2、把common\models\LoginForm.php復制到backend\models只要把LoginForm.php里面的方法getUser()修改一個單詞即可,如下

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

3、backend\config\main.php 只要修改

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

此外,在作修改時,請注意下命令空不要搞亂了。

到此,結(jié)束。

更多關于Yii相關內(nèi)容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結(jié)》、《php優(yōu)秀開發(fā)框架總結(jié)》、《smarty模板入門基礎教程》、《php日期與時間用法總結(jié)》、《php面向?qū)ο蟪绦蛟O計入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總

希望本文所述對大家基于Yii框架的PHP程序設計有所幫助。

相關文章

  • PHP中常見的錯誤與異常處理總結(jié)大全

    PHP中常見的錯誤與異常處理總結(jié)大全

    任何程序員在開發(fā)時都可能遇到過一些失誤,或其他原因造成錯誤的發(fā)生。當然,用戶如果不愿意或不遵循應用程序的約束,也會在使用時引起一些錯誤發(fā)生。下面這篇文章主要給大家介紹了關于PHP中常見的錯誤與異常處理,需要的朋友可以參考下,
    2017-08-08
  • 學習php中的正則表達式

    學習php中的正則表達式

    簡單的說,正則表達式是一種可以用于模式匹配和替換的強有力的工具。我們可以在幾乎所有的基于UNIX系統(tǒng)的工具中找到ta的身影。此外,象JavaScript這種客戶端的腳本語言也提供了支持。正則表達式已經(jīng)超出了某種語言或某個系統(tǒng)的局限,成為人們廣為接受的概念和功能。
    2014-08-08
  • thinkPHP5.0框架獨立配置與動態(tài)配置方法

    thinkPHP5.0框架獨立配置與動態(tài)配置方法

    這篇文章主要介紹了thinkPHP5.0框架獨立配置與動態(tài)配置方法,結(jié)合實例形式分析了thinkPHP5.0框架獨立配置與靜態(tài)配置的功能、實現(xiàn)技巧與相關注意事項,需要的朋友可以參考下
    2017-03-03
  • php 字符串中的\n換行符無效、不能換行的解決方法

    php 字符串中的\n換行符無效、不能換行的解決方法

    這篇文章主要介紹了php 字符串中的換行符無效、不能換行的解決方法,實際上是PHP的雙引號和單引號的使用問題,需要的朋友可以參考下
    2014-04-04
  • Laravel 錯誤提示本地化的實現(xiàn)

    Laravel 錯誤提示本地化的實現(xiàn)

    今天小編就為大家分享一篇Laravel 錯誤提示本地化的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-10-10
  • PHP 文件上傳限制問題

    PHP 文件上傳限制問題

    這篇文章主要介紹了PHP 文件上傳限制問題,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-09-09
  • php屏蔽錯誤及提示的方法

    php屏蔽錯誤及提示的方法

    在本篇文章里小編給大家分享的是關于php屏蔽錯誤及提示的方法,需要的朋友們可以學習下。
    2020-05-05
  • thinkPHP模型初始化實例分析

    thinkPHP模型初始化實例分析

    這篇文章主要介紹了thinkPHP模型初始化的方法,結(jié)合實例形式分析了thinkPHP模型初始化及數(shù)據(jù)庫操作的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-12-12
  • WordPress中is_singular()函數(shù)簡介

    WordPress中is_singular()函數(shù)簡介

    這篇文章主要介紹了WordPress中is_singular()函數(shù)簡介的相關資料,需要的朋友可以參考下
    2015-02-02
  • php+ajax注冊實時驗證功能

    php+ajax注冊實時驗證功能

    我們在網(wǎng)站上面注冊時,在輸入用戶名時,首先要進行無刷新驗證,這篇文章主要為大家詳細介紹了php+ajax注冊實時驗證功能,感興趣的小伙伴們可以參考一下
    2016-07-07

最新評論