Tuesday, July 3, 2012

working with cookie values in yii

If you are working with a lot of cookie values and want to shorten the code provided, then you
can use a helper as follows:
class Cookie
{
public static function get($name)
{
$cookie=Yii::app()->request->cookies[$name];
if(!$cookie)
return null;
return $cookie->value;
}
public static function set($name, $value, $expiration=0)
{
$cookie=new CHttpCookie($name,$value);
$cookie->expire = $expiration;
Yii::app()->request->cookies[$name]=$cookie;
}
}

After you drop this code into protected/components/Cookie.php, you will be able to
perform the following:
class TestController extends CController
{
public function actionIndex()
{
$cookie = Cookie::get('test');
if($cookie)
echo $cookie;
else
Cookie::set('test','I am a cookie!!');
}
}

No comments:

Post a Comment