我需要帮助!
我有一个使用数据库登录的工作机制,但有时我需要登录过程没有数据库(假用户使用)。
用户模型中的静态方法
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);
}
我也尝试过替代variat方法,如:
public static function findByRoot()
{
$model = new User();
$model->id = '1000';
$model->username = 'vasya';
$model->status = 10;
return $model;
}
Yii::$app->getUser()->login()
需要 UserIdentity
做auth:
\Yii::$app->getUser()->login(User::findByRoot());
如果我在login
方法中使用db输入真实姓名,则返回TRUE
并确认
但是如果放User::findByRoot()
(同一个对象),它也返回TRUE
但Yii::$app->user->identity
有NULL
问题是什么?
答案 0 :(得分:5)
Yii::$app->user->identity
会返回null
,以防无法找到用户的ID。要解决这个问题,首先要确保在这里提供正确的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;
}
您拥有的第二个选项是始终使用填充数据返回实例,因为您仍然使用虚假数据对其进行测试。
public static function findIdentity($id)
{
// just ignore the $id param here
return new static(array(
'updated_at' => '...',
'username' => '....',
// and the rest
));
}