Google News
logo
Yii framework - Interview Questions
Explain Sessions and Cookies in Yii Framework.
Sessions and cookies allow data to be persisted across multiple user requests. In plain PHP you may access them through the global variables $_SESSION and $_COOKIE, respectively. Yii encapsulates sessions and cookies as objects and thus allows you to access them in an object-oriented fashion with additional useful enhancements.
 
Sessions : Like requests and responses, you can get access to sessions via the session application component which is an instance of yii\web\Session, by default.
 
Opening and Closing Sessions : To open and close a session, you can do the following:
$session = Yii::$app->session;

// check if a session is already open
if ($session->isActive) ...

// open a session
$session->open();

// close a session
$session->close();

// destroys all data registered to a session.
$session->destroy();

 

Cookies : Yii represents each cookie as an object of yii\web\Cookie. Both yii\web\Request and yii\web\Response maintain a collection of cookies via the property named cookies. The cookie collection in the former represents the cookies submitted in a request, while the cookie collection in the latter represents the cookies that are to be sent to the user.

 

The part of the application dealing with request and response directly is controller. Therefore, cookies should be read and sent in controller.

 

Reading Cookies : You can get the cookies in the current request using the following code:

// get the cookie collection (yii\web\CookieCollection) from the "request" component

$cookies = Yii::$app->request->cookies;



// get the "language" cookie value. If the cookie does not exist, return "en" as the default value.

$language = $cookies->getValue('language', 'en');



// an alternative way of getting the "language" cookie value

if (($cookie = $cookies->get('language')) !== null) {

    $language = $cookie->value;

}



// you may also use $cookies like an array

if (isset($cookies['language'])) {

    $language = $cookies['language']->value;

}



// check if there is a "language" cookie

if ($cookies->has('language')) ...

if (isset($cookies['language'])) ...


Sending Cookies : 
You can send cookies to end users using the following code : 

// get the cookie collection (yii\web\CookieCollection) from the "response" component

$cookies = Yii::$app->response->cookies;



// add a new cookie to the response to be sent

$cookies->add(new \yii\web\Cookie([

    'name' => 'language',

    'value' => 'zh-CN',

]));



// remove a cookie

$cookies->remove('language');

// equivalent to the following

unset($cookies['language']);
Advertisement