我这个是参考网上的做的,已经成功了,这里贴出来做个记录
参考地址:http://www.yiichina.com/tutorial/332
1、创建数据库 eg:storage
2、将参考例子中的user表的结构复制到SQL中生成user表
CREATE TABLE IF NOT EXISTS `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(32) NOT NULL,
`authKey` varchar(100) NOT NULL DEFAULT '',
`accessToken` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
3、将项目文件里的数据库的配置文件(config文件夹里的db.php)的数据库名称改成自己建的数据库即rstorage
4、通过yii2的gii模块生成需要的模型和CURD操作
1)创建User.php模型
2)将生成的User.php文件修改如下:
3)将登录内容添加上后最终的User.php文件如下
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "user".
*
* @property string $id
* @property string $username
* @property string $password
* @property string $authKey
* @property string $accessToken
*/
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'user';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['username', 'password'], 'required'],
[['username'], 'string', 'max' => 50],
[['password'], 'string', 'max' => 32],
[['authKey', 'accessToken'], 'string', 'max' => 100]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'username' => Yii::t('app', 'Username'),
'password' => Yii::t('app', 'Password'),
'authKey' => Yii::t('app', 'Auth Key'),
'accessToken' => Yii::t('app', 'Access Token'),
];
}
/**
* @inheritdoc
*/
public static function findIdentity($id)
{
return User::findOne($id);
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return User::findOne(['access_token' => $token]);
}
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username)
{
$user = User::find()
->where(['username' => $username])
->asArray()
->one();
if($user){
return new static($user);
}
return null;
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
}
4)测试登录
点击login
输入账号密码(根据数据库里user表里的记录)eg:admin,123
登录成功后显示
点击logout即可退出
到此,登录就完成了,对于user.php文件中的修改我也没有深究修改成现在模型的原因,不过大概意思就是将原来的登录形式改成传统的根据数据库里的帐号密码进行登录即可。