$_SESSION objects

I have an object that I wish to register in $_SESSION application wide.

Where is the best place to do this?


$this->setState('$session_data', 'value');

That does not answer the question at all, which was: WHERE in the application (file) is the best place to register an object in $_SESSION:




if(!isset(Yii::app()->session['myObject'])) Yii::app()->session['myObject'] = new myClass;



I want to be able to use:


$myVariable = Yii::app()->session['myObject'];

then use that as I want:


$myVariable->saveInfo('myInfo');

That is, the class is instantiated only once for the session, with whatever the the object contains available application wide unique to that session.

Or is there a better way?

You could try something like this. Just make sure that the new class can be included somewhere.




// File: protected/config/main.php

return array(

...

'onBeginRequest' => array('Config', 'init'),

...

);






// File: protected/models/Config.php

class Config {

  public static function init() {

    if(!isset(Yii::app()->session['myObject'])) Yii::app()->session['myObject'] = new myClass;

  }

}



In this way, every request handles this. If you are using php 5.3, you can just use a lambda function instead of the array().

I think you’re looking for CWebUser (or more specifically, http://www.yiiframework.com/doc/api/CWebUser#setState-detail ). You can access anything you store in it via Yii::app()->user.