在Yii2中,您可以通过使用\yii\web\User类中的identityInterface对象访问当前用户的身份接口,如下所示

 \Yii::$app->user->identity->id;

有没有办法获取和设置额外的参数(不扩展identity类)?

基本上相当于Yii1。x getState(), ,而 setState() 方法在 CWebUser 像这样存储和检索会话信息

Yii::app()->user->setState("some_attribute",$value);
Yii::app()->user->getState('some_attribute',$defaultValue);
有帮助吗?

解决方案

好吧,这似乎是故意删除的,以避免"混乱"。见 https://github.com/yiisoft/yii2/issues/167.所以只有通过直接调用session类来做到这一点。

\Yii::$app->session->set('user.attribute',$value);
\Yii::$app->session->get('user.some_attribute');

因为它现在直接存储在会话中,没有前缀,所以最好用标识符命名密钥,如 user.xxxx 以避免在应用程序的不同点与其他键集发生碰撞。

其他提示

向user添加属性的最佳方法是在User类中创建public属性。

class Yiidentity extends ActiveRecord implements \yii\web\IdentityInterface{
       public $awesomeAttribute = "foo";
}

如何使用:

Yii::$app->user->identity->awesomeAttribute;

在Yii2 \Yii::$app->用户->身份 包含identityClass的实例。所以,如果你想要一些与identityClass相关的数据-只需像identityClass的实例一样使用它。

你也可以使用 吸气剂,吸气剂 功能以包括用于用户的附加身份信息。例如,检索 fullname 从配置文件表。

class User extends ActiveRecord implements \yii\web\IdentityInterface
{
    // Other code goes here...       
    public function getFullname()
    {
        $profile = Profile::find()->where(['user_id'=>$this->id])->one();
        if ($profile !==null)
            return $profile->fullname;
        return false;
    }
}

然后,您可以使用它,就好像您有一个名为 fullname, ,像这样

Yii::$app->user->identity->fullname;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top