[英]How to login Yii2 without database?
我需要幫助!
我有一個工作機制登錄DB,但有時我需要登錄過程沒有DB (假用戶使用)。
用戶模型中的靜態方法
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的實現
做認證:
\Yii::$app->getUser()->login(User::findByRoot());
如果我在login
方法中從db中輸入真實名稱,則返回TRUE
,這沒關系
但是,如果把User::findByRoot()
同一個對象),它返回太TRUE
,但Yii::$app->user->identity
有NULL
什么問題?
Yii::$app->user->identity
如果找不到用戶的id,則返回null
。 要解決這個問題,首先要確保在這里提供正確的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
));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.