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

时间:2015-10-09 10:08:19

标签: php authentication yii2

我需要帮助!

我有一个使用数据库登录的工作机制,但有时我需要登录过程没有数据库(假用户使用)。

用户模型中的静态方法

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()(同一个对象),它也返回TRUEYii::$app->user->identityNULL

问题是什么?

1 个答案:

答案 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 
    ));
}
相关问题