20

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

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

Is there a way to get and set additional parameters (without extending the identity class)?

Basically a equivalent of Yii 1.x getState(), and setState() methods in CWebUser to store and retrieve session information like this

Yii::app()->user->setState("some_attribute",$value);
Yii::app()->user->getState('some_attribute',$defaultValue);

4 Answers 4

24

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.

12

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;
2
  • 1
    In my opinion this is the correct answer. No need to call the session class here. Thank you, this was exactly what I was looking for!
    – gotcha
    Aug 20, 2015 at 6:21
  • Where would you put this class in the context of basic and advanced app? Thanks!
    – johnsnails
    Nov 24, 2016 at 21:05
9

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.

1
  • 1
    Could you please elaborate on how this would be done? How would I create a new attribute to use elsewhere in the application?
    – Dubby
    Apr 13, 2015 at 6:05
2

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.