How to add more user identity session attributes in Yii2?

前端 未结 4 1151
说谎
说谎 2021-02-01 05:54

In Yii2 you can access the identity interface for the current user by using the identityInterface object from within the \\yii\\web\\User class with something like this

4条回答
  •  时光说笑
    2021-02-01 06:30

    You could also use a getter function to include additional identity information for the user. For example, retrieve fullname from a profile table.

    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;
        }
    }
    

    Then, you can use it as if you have an attribute named fullname, like so

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

提交回复
热议问题