簡體   English   中英

如何在Yii2中添加更多用戶身份會話屬性?

[英]How to add more user identity session attributes in Yii2?

在Yii2中,您可以使用\\ yii \\ web \\ User類中的identityInterface對象訪問當前用戶的標識界面,如下所示

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

有沒有辦法獲取和設置其他參數(不擴展標識類)?

基本上Yii的1.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 所以通過直接調用會話類來實現此目的的唯一方法。

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

因為它現在直接存儲在沒有前綴的會話中,所以最好使用user.xxxx標識符來命名密鑰,以避免與應用程序的不同點處的某些其他密鑰集沖突。

向用戶添加屬性的最佳方法是在用戶類中創建公共屬性。

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

如何使用:

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

在Yii2 \\ Yii :: $ app-> user-> identity中包含identityClass的實例。 所以,如果你想要一些與identityClass相關的數據 - 就像使用identityClass的實例一樣。

您還可以使用getter函數為用戶包含其他身份信息。 例如,從配置文件表中檢索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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM