[英]How to login Yii2 without database?
I need a help! 我需要帮助!
I have a working mechanism login with DB but sometimes i need get login process without DB (fake user use). 我有一个工作机制登录DB,但有时我需要登录过程没有DB (假用户使用)。
Static method in User model 用户模型中的静态方法
public static function findByRoot()
{
$arr = [
'id' => 100,
'created_at' => 1444322024,
'updated_at' => 1444322024,
'username' => 'vasya',
'auth_key' => 'aagsdghfgukfyrtweri',
'password_hash' => 'aa2gsdg123hfgukfyrtweri',
'email' => 'some@email',
'status' => 10,
];
return new static($arr);
}
I too tried alternative variat method like: 我也尝试过替代variat方法:
public static function findByRoot()
{
$model = new User();
$model->id = '1000';
$model->username = 'vasya';
$model->status = 10;
return $model;
}
Yii::$app->getUser()->login()
requires implements from UserIdentity Yii::$app->getUser()->login()
需要UserIdentity的实现
Do auth: 做认证:
\Yii::$app->getUser()->login(User::findByRoot());
If I put real name from db in login
method it returned TRUE
and that's OK 如果我在
login
方法中从db中输入真实名称,则返回TRUE
,这没关系
But if put User::findByRoot()
(the same object) it returned too TRUE
but Yii::$app->user->identity
has NULL
但是,如果把
User::findByRoot()
同一个对象),它返回太TRUE
,但Yii::$app->user->identity
有NULL
What's problem? 什么问题?
Yii::$app->user->identity
returns null
in case it can't find user's id. Yii::$app->user->identity
如果找不到用户的id,则返回null
。 To fix that, first of all make sure, you supply the right id here: 要解决这个问题,首先要确保在这里提供正确的ID:
public static function findIdentity($id)
{
// dump $id here somehow, does it belong to the static collection?
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
Second option you have, is to always return the instance with filled data, since you use a fake data to test it anyway. 您拥有的第二个选项是始终使用填充数据返回实例,因为您无论如何都使用虚假数据进行测试。
public static function findIdentity($id)
{
// just ignore the $id param here
return new static(array(
'updated_at' => '...',
'username' => '....',
// and the rest
));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.