Yii::app()->user->setState()

Hello all,

Every once in a while I run across something in Yii where the docs do not provide a sufficient answer. Thankfully these cases are rare. :)

I am storing some data in the user session, and figured to use Yii::app()->user->setState() from a controller. However, the documentation says: (bold part by me)

I know there is Yii::app()->session[‘var’] = ‘value’, but that is more low level and won’t handle possible duplicates (setState() adds a prefix).

Is there another obvious way I should be dealing with storing information in the user session?

setState is aimed at data that only applies to logged in users. If you want something to stick to a visitor then you really want Yii::app()->session[‘var’]. Yii::app()->session[‘var’] is a bit more low level (if you can call emulating state over a stateless protocol in an interpreted language low level) but it is just a wrapper for $_SESSION, there is only so much sugar you can add.

TLDR: there isn’t really any other “better” way.

???

CWebUser::setState() and CWebUser::getState() should work for any user, no matter if he/she is logged in or not.

Sorry you’re right, I don’t know where I got that idea from. However logout does destroy the whole session by default and if you pass in false to CWebUser::logout() it will destroy states. So if you want data to persist across login/logout you would need to tell CWebUser::logout() not to destroy the session and store it in Yii::app()->session[‘variable’].

I see.

Thanks for the information.

this is the good way CWebUser::setState() and CWebUser::getState()

it will work for any case

Thouse are not static methods

So better is to use




Yii::app()->user->setState($key,$val, $defaultVall = null )



In session case:




config

'components'=>array(

    'session'=>array(

          'autoStart'=>true

    )


)


Yii::app()->session->add($key,$value);