当前位置:首页 > PHP教程 > PHP常见问题

YII Framework框架使用YIIC快速创建YII应用之migrate用法实例详解

本文实例讲述了yii framework框架使用yiic快速创建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. */

在我们开发程序的过程中,数据库的结构也是不断调整的。我们的开发中要保证代码和数据库库的同步。因为我们的应用离不开数据库。例如: 在开发过程中,我们经常需要增加一个新的表,或者我们后期投入运营的产品,可能需要为某一列添加索引。我们必须保持数据结构和代码的一致性。如果代码和数据库不同步,可能整个系统将无法正常运行。出于这个原因。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

consolemigrationsm130524_201442_init.php

use yiidbschema; use yiidbmigration; 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成功

2、linux下命令一样(此处略)

二、使用gii创建模型

此处略,很简单的步聚。

注:把admin模型创在 backend/models下面 (放哪里看个人喜好)
代码如下

namespace backendmodels; use yii; use yiibasenotsupportedexception; use yiibehaviorstimestampbehavior; use yiidbactiverecord; use yiiwebidentityinterface; /** * 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、consolecontrollers创建initcontroller.php

/** * * @author chan <maclechan@qq.com> */ namespace consolecontrollers; use backendmodelsadmin ; class initcontroller extends yiiconsolecontroller { /** * 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 "$en"; } } return 1; // 命令行返回1表示有异常 } return 0; // 返回0表示一切ok } }

2、使用命令:

在项目根目下,右键选择user composer here(前提是安装了全局的composer),
yii init/admin

到此,打开数据表看下,己经有了数据。

四、后台登陆验证

1、backendcontrollerssitecontroller.php 里actionlogin方法不用变

2、把commonmodelsloginform.php复制到backendmodels只要把loginform.php里面的方法getuser()修改一个单词即可,如下

public function getuser() { if ($this->_user === false) { $this->_user = admin::findbyusername($this->username); } return $this->_user; }

3、backendconfigmain.php 只要修改

'user' => [ 'identityclass' => 'backendmodelsadmin', 'enableautologin' => true, ],

此外,在作修改时,请注意下命令空不要搞乱了。

到此,结束。

更多关于yii相关内容感兴趣的读者可查看本站专题:《yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于yii框架的php程序设计有所帮助。



【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!