Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add more user identity session attributes in Yii2?

Tags:

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);
like image 742
Manquer Avatar asked Aug 01 '14 11:08

Manquer


1 Answers

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.

like image 122
Manquer Avatar answered Sep 18 '22 01:09

Manquer