热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

这篇文章主要介绍了YIIFramework框架使用YIIC快速创建YII应用之migrate用法,详细分析了migrate的功能与用法,并给出创建登录后台的实例讲述了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

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

使用命令行来创建admin数据库

1、win7下使用命令:

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

即创建数据表 admin成功

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

二、使用gii创建模型

此处略,很简单的步聚。

注:把admin模型创在 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创建InitController.php

/**
 *
 * @author chan 
 */
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

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

四、后台登陆验证

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,
],

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

到此,结束。

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

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


推荐阅读
  • 本文介绍了在Mac上搭建php环境后无法使用localhost连接mysql的问题,并通过将localhost替换为127.0.0.1或本机IP解决了该问题。文章解释了localhost和127.0.0.1的区别,指出了使用socket方式连接导致连接失败的原因。此外,还提供了相关链接供读者深入了解。 ... [详细]
  • Metasploit攻击渗透实践
    本文介绍了Metasploit攻击渗透实践的内容和要求,包括主动攻击、针对浏览器和客户端的攻击,以及成功应用辅助模块的实践过程。其中涉及使用Hydra在不知道密码的情况下攻击metsploit2靶机获取密码,以及攻击浏览器中的tomcat服务的具体步骤。同时还讲解了爆破密码的方法和设置攻击目标主机的相关参数。 ... [详细]
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的详细步骤
    本文详细介绍了搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的步骤,包括环境说明、相关软件下载的地址以及所需的插件下载地址。 ... [详细]
  • PHP设置MySQL字符集的方法及使用mysqli_set_charset函数
    本文介绍了PHP设置MySQL字符集的方法,详细介绍了使用mysqli_set_charset函数来规定与数据库服务器进行数据传送时要使用的字符集。通过示例代码演示了如何设置默认客户端字符集。 ... [详细]
  • 本文介绍了如何使用php限制数据库插入的条数并显示每次插入数据库之间的数据数目,以及避免重复提交的方法。同时还介绍了如何限制某一个数据库用户的并发连接数,以及设置数据库的连接数和连接超时时间的方法。最后提供了一些关于浏览器在线用户数和数据库连接数量比例的参考值。 ... [详细]
  • 本文介绍了Redis的基础数据结构string的应用场景,并以面试的形式进行问答讲解,帮助读者更好地理解和应用Redis。同时,描述了一位面试者的心理状态和面试官的行为。 ... [详细]
  • 本文介绍了在Hibernate配置lazy=false时无法加载数据的问题,通过采用OpenSessionInView模式和修改数据库服务器版本解决了该问题。详细描述了问题的出现和解决过程,包括运行环境和数据库的配置信息。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 本文由编程笔记小编整理,介绍了PHP中的MySQL函数库及其常用函数,包括mysql_connect、mysql_error、mysql_select_db、mysql_query、mysql_affected_row、mysql_close等。希望对读者有一定的参考价值。 ... [详细]
  • 本文介绍了Oracle数据库中tnsnames.ora文件的作用和配置方法。tnsnames.ora文件在数据库启动过程中会被读取,用于解析LOCAL_LISTENER,并且与侦听无关。文章还提供了配置LOCAL_LISTENER和1522端口的示例,并展示了listener.ora文件的内容。 ... [详细]
  • 本文详细介绍了Linux中进程控制块PCBtask_struct结构体的结构和作用,包括进程状态、进程号、待处理信号、进程地址空间、调度标志、锁深度、基本时间片、调度策略以及内存管理信息等方面的内容。阅读本文可以更加深入地了解Linux进程管理的原理和机制。 ... [详细]
  • 学习SLAM的女生,很酷
    本文介绍了学习SLAM的女生的故事,她们选择SLAM作为研究方向,面临各种学习挑战,但坚持不懈,最终获得成功。文章鼓励未来想走科研道路的女生勇敢追求自己的梦想,同时提到了一位正在英国攻读硕士学位的女生与SLAM结缘的经历。 ... [详细]
author-avatar
月雨淅淅
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有