Sessions
1Presentation
The session system allows temporary storage of variables, which are linked to a visitor. The advantage is to perform
processing in a controller as a function of the processing carried out previously in the controllers executed beforehand.
Each session is linked to a browser by means of a cookie placed on the first access. This is transparent because it is managed by the framework.
The session management object is created automatically by Temma, if the configuration provides for it.
2Configuration
In the etc/temma.php file, you can define how sessions are stored (see configuration documentation).
Please note that if no source is specified, Temma uses PHP's native session mechanism. Note that PHP stores session data in files, which are locked when accessed. This means that only one request can access them at a time, which can create lockouts if you have long-running requests (for example, if you use event controllers).
3Session object
In controllers, the session object is available by writing:
$this->_session
In the other objects managed by the dependency injection component, the session object can be accessed by writing:
$this->_loader->session
4Reading data
To read data from the session, just use the object as an associative array:
$currentUser = $this->_session['user'];
To find out if a session variable exists, or if it is empty:
// is the variable defined?
if (isset($this->_session['myVariable']))
doSomething();
// is the variable empty?
if (empty($this->_session['myOtherVariable']))
doSomethingElse();
// undefined variable: use a default value
$var = $this->_session['myVariable'] ?? 'defaultValue';
// undefined or empty variable: use a default value
$var = $this->_session['myVariable'] ?: 'defaultValue';
With the get() method, you can read a session variable, specifying a default value which is returned if the data is not present in the session:
$var = $this->_session->get('myVariable', 'Default value');
It is possible to retrieve all the session variables with the getAll() method:
$sessVariables = $this->_session->getAll();
$currentUser = $sessVariables['user'];
$basket = $sessVariables['basket'];
It is also possible to retrieve all session variables whose name begins with a certain prefix, using the getPrefix() method:
$names = $this->_session->getPrefix('name-');
foreach ($names as $nameKey => $nameValue) {
print($nameKey . ' : ' . $nameValue);
}
/*
* For example, it might show:
* name-1 : Alice
* name-2 : Bob
* name-3 : Camille
*/
print($this->_session['name-1']);
// write "Alice"
5Writing data
To create or modify a session variable:
$this->_session['myVariable'] = $value;
If the value assigned to the variable is null, the variable is deleted from the session.
To read and write data, the session management object is used like an array. But this does not allow to write
values directly to multi-dimensional arrays.
To modify a multidimensional array, you must first retrieve the complete array, modify it, then overwrite the session variable:
// it does not work
$this->_session['user']['name'] = 'Einstein';
// this is how to do it
$user = $this->_session['user'];
$user['name'] = 'Einstein';
$this->_session['user'] = $user;
6Deleting data
To destroy a session variable:
unset($this->_session['myVariable']);
To delete all the variables from the session:
$this->_session->clean();
7Extracting data
Data extraction consists in reading session variables and then deleting them from the session.
It is possible to extract data from the session, i.e. to read and delete it from the session in a single call to the extract() method:
$value = $this->_session->extract('myVariable');
// is equivalent to
$value = $this->_session['myVariable'];
unset($this->_session['myVariable']);
// extract() can also take a default value
$value = $this->_session->extract('myVariable', 'default value');
You can also extract all session variables whose names begin with a certain prefix. The retrieved variables are deleted from the session. To do this, use the extractPrefix() method:
$users = $this->_session->extractPrefix('user-');
foreach ($users as $login => $name) {
print("$login : $name");
}
/*
* For example, it might show:
* jrambo : John Rambo
* jconnor : John Connor
* jwick : John Wick
*/
8Flash variables
8.1Principle
Flash variables are session variables with a very limited lifespan. The next time a page is loaded, they are extracted (and therefore deleted) from the session, and made available in template variables.
To make a session variable a flash variable, simply prefix its name with two underscores (__).
8.2Example 1
Let's imagine an Article controller with three actions:
- view: Displays the contents of an article, based on its identifier passed as a parameter. If the article doesn't exist, the action redirects to /article/info, having first created the flash variable __status with the value unknown_article.
- list: Displays the list of articles. If no item exists, the action redirects to /article/info, having first created the flash variable __status with the value empty_list.
- info: displays an error message, depending on the value of flash variable __status.
Here is the controllers/Article.php file:
<?php
/** Article management controller. */
class Article extends \Temma\Web\Controller {
/** Action that displays an article based on its identifier. */
public function view(int $articleId) {
// retrieve the article
$article = ...
// check the article
if (!$article) {
// create flash variable
$this->_session['__status'] = 'unknown_article';
// redirect
return $this->_redirect('/article/info');
}
}
/** Action that displays the list of articles. */
public function liste() {
// retrieve articles
$articles = ...
// check articles
if (!$articles) {
// create flash variable
$this->_session['__status'] = 'empty_list';
// redirect
return $this->_redirect('/article/info');
}
}
/** Action that displays information. */
public function info() {
// no processing
}
}
- Line 8: article retrieval by identifier.
-
Lines 10 to 15: processing when there is no article with this identifier.
- Line 12: creation of flash variable.
- Line 14: redirection.
- Line 20: article list retrieval.
-
Lines 22 to 27: processing when there are no articles.
- Line 24: creation of flash variable.
- Line 26: redirection.
Here is the templates/article/info.tpl file:
<html>
<body>
<h1>Informations</h1>
{* displays a message based on the flash variable *}
{if $__status == 'unknown_article'}
The requested article does not exist.
{elseif $__status == 'empty_liste'}
There are no articles to display.
{else}
An error has been encountered.
{/if}
</body>
</html>
8.3Example 2
In this second example, we're going to evolve the Article controller. When the view action encounters an error (the article doesn't exist), it redirects to the list action, to display the list of articles.
The list action continues to redirect to info if it has no items to display. On the other hand, if you were redirected from the view action, it is the latter's status (unknown_article) that is propagated, and not the one indicating that there are no articles (empty_list).
Here is the controllers/Article.php file:
<?php
/** Article management controller. */
class Article extends \Temma\Web\Controller {
/** Action that displays an article based on its identifier. */
public function voir(int $articleId) {
// retrieve the article
$article = ...
// check the article
if (!$article) {
// create flash variable
$this->_session['__status'] = 'unkonwn_article';
// redirect
return $this->_redirect('/article/info');
}
}
/** Action that displays the list of articles. */
public function liste() {
// retrieve articles
$articles = ...
// check articles
if (!$articles) {
// create flash variable
if ($this['__status'])
$this->_session['__statut'] = $this['__statut'];
else
$this->_session['__statut'] = 'liste_vide';
// redirect
return $this->_redirect('/article/info');
}
}
/** Action that displays information. */
public function info() {
// no processing
}
}
Lines 22 to 30: processing when there are no items.
- Line 24: Checks whether template variable __status exists and is not empty. If so, a flash variable __status has been defined on the previous page.
- Line 25: if template variable __status exists and is not empty, use its value to create a new flash variable __status.
- Line 27: otherwise, create a flash variable with the value empty_list.
- Line 29: redirection.