Having several Yii apps sharing the same session, I REALLY needed a way of dividing the variables as several developers are working on the project and it would be simply impossible to make sure one wasn't overwriting data of another.
I decided to use objects instead of arrays though as this will allow greater flexibility in the future. Additionally, it would be possible to use an object implementing ArrayAccess if array style access becomes important.
Now, for the code. Here is my modified session class :
class MySession extends CHttpSession
{
public function setInstance($sessionName, $className='stdClass')
{
if (!isset($_SESSION[$sessionName])) {
$_SESSION[$sessionName] = new $className();
}
}
}
When I need to add a division, I declare it like so :
class MyWebUser extends CWebUser
{
public function afterLogin($fromCookie)
{
Yii::app()->session->setInstance('secretData');
Yii::app()->session['secretData']->secret = 'superSecretThing';
[....]
}
}
... though of course this could be anywhere. The important thing is that it only needs to be done once.
Once the object has been initialized by the 'setInstance' method, it can be accessed and modified from any other parts of the code without having to set its instance again.
class UserController extends CController
{
public function actionTest1()
{
Yii::app()->session['secretData']->secret = 'ohNoesYouFoundMySecret';
}
public function actionTest2()
{
var_dump(Yii::app()->session['secretData']->secret);
}
}