如何在没有数据库的情况下登录Yii2?

Ado*_*obe 4 php authentication yii2

我需要帮助!

我有一个工作机制登录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);
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过替代variat方法:

public static function findByRoot()
  {
    $model = new User();
    $model->id = '1000';
    $model->username = 'vasya';
    $model->status = 10;
    return $model;
  }
Run Code Online (Sandbox Code Playgroud)

Yii::$app->getUser()->login()需要UserIdentity的工具

做认证:

\Yii::$app->getUser()->login(User::findByRoot());
Run Code Online (Sandbox Code Playgroud)

如果我在login方法中输入db的实名,那就返回了TRUE,那没关系

但是如果放User::findByRoot()(同一个对象)它也会返回TRUE但是Yii::$app->user->identityNULL

什么问题?

Yan*_*ang 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;
}
Run Code Online (Sandbox Code Playgroud)

您拥有的第二个选项是始终使用填充数据返回实例,因为您无论如何都使用虚假数据进行测试.

public static function findIdentity($id)
{
    // just ignore the $id param here
    return new static(array(
        'updated_at' => '...',
        'username' => '....',
        // and the rest 
    ));
}
Run Code Online (Sandbox Code Playgroud)