如何在 Yii2 中添加更多用户身份会话属性? [英] How to add more user identity session attributes in Yii2?
问题描述
在 Yii2 中,您可以通过使用来自 \yii\web\User 类中的 identityInterface 对象来访问当前用户的身份接口
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;
有没有办法获取和设置额外的参数(不扩展身份类)?
基本上相当于 Yii 1.x getState()
和 CWebUser
中的 setState()
方法来存储和检索会话信息,如这个
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);
推荐答案
好吧,这似乎是有意删除以避免混淆".请参阅 https://github.com/yiisoft/yii2/issues/167.所以唯一的办法就是直接调用会话类.
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');
因为它现在直接存储在会话中而没有前缀,所以最好使用像 user.xxxx
这样的标识符命名键以避免与应用程序不同点的其他键集冲突.
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.
这篇关于如何在 Yii2 中添加更多用户身份会话属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!