Hi everybody,
faced the problem to store objects in the User-Session, but didn’t want to do the (un-)serializing of objects manually.
I enhanced CWebUser with following:
/**
* Returns the value of a variable that is stored in user session.
*
* This function is designed to be used by CWebUser descendant classes
* who want to store additional user information in user session.
* A variable, if stored in user session using {@link setState} can be
* retrieved back using this function.
*
* @param string $key variable name
* @param mixed $defaultValue default value
* @return mixed the value of the variable. If it doesn't exist in the session,
* the provided default value will be returned
* @see setState
*/
public function getState($key,$defaultValue=null)
{
$key=$this->getStateKeyPrefix().$key;
$return = isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
if(substr($return, 0, 10) == '{isObject}' )
$return = unserialize(substr($return, 10));
return $return;
}
/**
* Stores a variable in user session.
*
* This function is designed to be used by CWebUser descendant classes
* who want to store additional user information in user session.
* By storing a variable using this function, the variable may be retrieved
* back later using {@link getState}. The variable will be persistent
* across page requests during a user session.
*
* @param string $key variable name
* @param mixed $value variable value
* @param mixed $defaultValue default value. If $value===$defaultValue, the variable will be
* removed from the session
* @see getState
*/
public function setState($key,$value,$defaultValue=null)
{
if(is_object($value))
$value = '{isObject}'.serialize($value);
if(is_object($defaultValue))
$defaultValue = '{isObject}'.serialize($defaultValue);
$key=$this->getStateKeyPrefix().$key;
if($value===$defaultValue)
unset($_SESSION[$key]);
else
$_SESSION[$key]=$value;
}
Best regards,
Schmu