一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - PHP教程 - YII Framework框架使用YIIC快速創建YII應用之migrate用法實例詳解

YII Framework框架使用YIIC快速創建YII應用之migrate用法實例詳解

2020-12-29 16:38眼鏡群 PHP教程

這篇文章主要介紹了YII Framework框架使用YIIC快速創建YII應用之migrate用法,詳細分析了migrate的功能與用法,并給出創建登錄后臺的實例講述了migrate的相關使用技巧,需要的朋友可以參考下

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

yii migrate

查看幫助

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
/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.
*/

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

功能正如描述。主要提供了數據庫遷移功能。

命令格式

yiic migrate [action] [parameter]

action參數用來制定執行哪一個遷移任務。可以一使用

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

如果沒有action參數,默認為up

parameter根據action的不同而有所變化。

上述例子中給出了說明。

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

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

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

補充:yii2.0使用migrate創建后臺登陸

重新創建一張數據表來完成后臺登陸驗證

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

一、使用Migration創建表admin

console\migrations\m130524_201442_init.php

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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);
  }
}

使用命令行來創建admin數據庫

1、win7下使用命令:

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

即創建數據表 admin成功

YII Framework框架使用YIIC快速創建YII應用之migrate用法實例詳解

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

二、使用gii創建模型

此處略,很簡單的步聚。

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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創建InitController.php

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 *
 * @author chan <[email protected]>
 */
namespace console\controllers;
use backend\models\Admin ;
class InitController extends \yii\console\Controller
{
  /**
   * Create init user
   */
  public function actionAdmin()
  {
    echo "創建一個新用戶 ...\n";         // 提示當前操作
    $username = $this->prompt('User Name:');    // 接收用戶名
    $email = $this->prompt('Email:');        // 接收Email
    $password = $this->prompt('Password:');     // 接收密碼
    $model = new AgAdmin();              // 創建一個新用戶
    $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

YII Framework框架使用YIIC快速創建YII應用之migrate用法實例詳解

到此,打開數據表看下,己經有了數據。

四、后臺登陸驗證

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

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

?
1
2
3
4
5
6
7
public function getUser()
{
    if ($this->_user === false) {
      $this->_user = Admin::findByUsername($this->username);
    }
    return $this->_user;
}

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

?
1
2
3
4
'user' => [
  'identityClass' => 'backend\models\Admin',
  'enableAutoLogin' => true,
],

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

到此,結束。

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 网址在线观看你懂我意思吧免费的 | 亚洲精品乱码久久久久久蜜桃图片 | 日本精品久久久久久久久免费 | 果冻传媒i91media免费 | 亚洲精品免费观看 | 国产爱啪啪 | 手机能看的黄色网站 | 思敏1一5集国语版免费观看 | 草莓香蕉绿巨人丝瓜榴莲18 | 和岳m的小说 | yellow最新视频2019 | 男人搡女人视频免费看 | 日本一卡2卡3卡4卡乱 | 精品久久久久久影院免费 | 精品视频 久久久 | 男人的天堂在线观看视频不卡 | xxxxxx国产精品视频 | 日本中文字幕二区三区 | 欧美日韩在线一区 | 国产高清在线观看 | 国产成人夜色影视视频 | 免费视频大全 | 国产91青青成人a在线 | 天堂资源在线www中文 | 小SAO货边洗澡边CAO你动漫 | 亚洲高清在线视频 | 美女污视频 | 四虎影视在线永久免费观看 | 国产成人高清精品免费观看 | 楚乔传第二部免费观看全集完整版 | 精品国产福利片在线观看 | 国产中文字幕 | 精品视频一区二区三区免费 | 91国内精品久久久久怡红院 | 日韩欧美国产免费看清风阁 | 四虎最新永久免费视频 | 午夜一级 | 国产午夜精品久久理论片小说 | 香蕉eeww99国产在线观看 | 我不卡影院手机在线观看 | 午夜看片a福利在线观看 |