A free and open-source book on ZF3 for beginners


15.3. Session Manager

ZF3 provides a special service called SessionManager which belongs to Zend\Session namespace. This service is a usual ZF3 service and is automatically registered in service manager. You can get an instance of the SessionManager service in a factory class with the following code:

// Use alias for the SessionManager class.
use Zend\Session\SessionManager;

// Retrieve an instance of the session manager from the service manager.
$sessionManager = $container->get(SessionManager::class);

So, what does the SessionManager do? Actually, it does everything for session to run. The summary of its most useful methods is provided in the table 15.1 below:

Table 15.1. Methods provided by the SessionManager class
Method Description
sessionExists() Checks whether session exists and currently active.
start($preserveStorage = false) Starts the session (if not started yet).
destroy(array $options = null) Ends the session.
getId() Returns session ID.
setId() Sets session ID.
regenerateId() Regenerates the session ID.
getName() Returns session name.
setName() Overrides the default session name from php.ini.
rememberMe($ttl = null) Sets session cookie lifetime (in seconds).
forgetMe() Set a zero lifetime for the session cookie (the cookie will expire when browser is closed).
expireSessionCookie() Expires the session cookie immediately.
isValid() Executes session validators.

As you can see from the table above, the SessionManager can start the session and end it, check if session exists, and set session parameters (such as cookie expiration). It also provides a validator chain that may contain session validators (those validators allow to prevent hacker attacks on session data).

15.3.1. Providing Session Configuration

The SessionManager class on initialization reads the application configuration, so you can set up the session parameters conveniently. To do that, modify your APP_DIR/config/autoload/global.php as follows:

<?php
use Zend\Session\Storage\SessionArrayStorage;
use Zend\Session\Validator\RemoteAddr;
use Zend\Session\Validator\HttpUserAgent;

return [
    // Session configuration.
    'session_config' => [
        // Session cookie will expire in 1 hour.
        'cookie_lifetime' => 60*60*1,     
        // Session data will be stored on server maximum for 30 days.
        'gc_maxlifetime'     => 60*60*24*30, 
    ],
    // Session manager configuration.
    'session_manager' => [
        // Session validators (used for security).
        'validators' => [
            RemoteAddr::class,
            HttpUserAgent::class,
        ]
    ],
    // Session storage configuration.
    'session_storage' => [
        'type' => SessionArrayStorage::class
    ],
    
    // ...
];

We modify global.php file here, because sessions may be used by any module in your website and do not depend on environment.

As you can see, the session configuration is stored under three keys:

15.3.2. Making the Session Manager the Default One

In ZF3, many components use the session manager implicitly (for example, FlashMessenger controller plugin and view helper uses session to save messages between HTTP requests). To let such components use the session manager you just configured, you'll have to make it "the default one" by instantiating it as early as possible. For example, you can instantiate the session manager in your module's onBootstrap() method, as follows:

<?php
namespace Application;

use Zend\Mvc\MvcEvent;
use Zend\Session\SessionManager;

class Module
{
    //...
    
    /**
     * This method is called once the MVC bootstrapping is complete. 
     */
    public function onBootstrap(MvcEvent $event)
    {
        $application = $event->getApplication();
        $serviceManager = $application->getServiceManager();
        
        // The following line instantiates the SessionManager and automatically
        // makes the SessionManager the 'default' one.
        $sessionManager = $serviceManager->get(SessionManager::class);
    }
}

Making the session manager the default one is very important, because otherwise you'll have to explicitly pass it to every component depending on the session manager, which is rather boring.


Top