Documentation

Sessions

Table of Contents 

Presentation

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.

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

Reading 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';

It is possible to retrieve all the session variables with the getAll() method:

$sessVariables = $this->_session->getAll();
$currentUser = $sessVariables['user'];
$basket = $sessVariables['basket'];

Writing 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;

Deleting data

To destroy a session variable:

unset($this->_session['myVariable']);

To delete all the variables from the session:

$this->_session->clean();
Previous: Dependency injection
Next: Data sources

Table of Contents