maclechan 2015-05-25 09:36:39 21702次浏览 2条评论 8 2 0

源文
(注:高级应用)
重新创建一张数据表admin来完成后台登陆验证。
为了大家看得明白,直接贴代码
一、使用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.');  
    }  

注:剩下的和common/models/User里面的是一样的

三、使用migrate 为后如初使化一个登陆帐号

1、console\controllers创建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 "创建一个新用户 ...\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,  
            ],  

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

到此,结束。

觉得很赞
  • 评论于 2015-05-26 10:03 举报

    请问migrate有什么用处?
    以及console的用处是什么?

    2 条回复
    评论于 2015-05-26 11:50 回复

    migrate是一个数据库迁移工具,平时的开发过程中体会不到优越性。console这里面的东西其实是很少用到的。都是用命令来操作!

    评论于 2015-05-26 12:19 回复

    哦,比如说我的数据从MySQL迁移到PGSQL的时候能够做到最大化兼容(某些MYSQL特有的写法或功能做迁移的时候YII可以自动替换成PG类似功能或写法)?
    console我知道是命令行操作,目的是和其他非浏览器客户端(比如硬件设备)做对接用的吗?

  • 评论于 2017-03-26 10:04 举报

    那基础版本如何创建User;?

    觉得很赞
您需要登录后才可以评论。登录 | 立即注册