How to add more user identity session attributes in Yii2?

前端 未结 4 1140
说谎
说谎 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:26

    In Yii2 \Yii::$app->user->identity contain instance of the identityClass. So, if you want some identityClass-related data - just use it like instance of the identityClass.

    0 讨论(0)
  • 2021-02-01 06:30

    The best way to add attributes to user is creating public attribute in your User Class.

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

    How to use:

    Yii::$app->user->identity->awesomeAttribute;
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2021-02-01 06:34

    Okay it seems this was removed intentionally to avoid "confusion". See https://github.com/yiisoft/yii2/issues/167. So the only way to do this by calling the session class directly.

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

    Because it now stored directly in session without prefix it is best to namespace the keys with identifiers like user.xxxx to avoid collision with some other key set at different point of the application.

    0 讨论(0)
提交回复
热议问题