huuthuan-nguyen
9/17/2018 - 7:06 AM

Zend Framework 3: Sessions

Zend Framework 3: Sessions

Why use Zend Session over $_SESSION?

Zend provided a wrapper around PHP Session, it takes some pros:

  • OOP, so you can use it consistently in your MVC application.
  • Namespace, different models can store data without naming conflicts.
  • Zend provided session validators, so it is more difficult for a mailicious user to hack.
  • $_SESSION superglobal array makes testing your website more difficult.
  • It is possible to implement custom data storages like Database, Redis, Memcached.

Install

php composer.phar require zendframework/zend-session

Config

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

return [
    // Session Configuration
    'session_config' => [
        // Session cookie will expried 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' => [
        'validators' => [
            // Session validators (use for security) 
            RemoteAddr::class,
            HttpUserAgent::class
        ],
    ],
    // Session storage configurations
    'session_storage' => [
        'type' => SessionArrayStorage::class
    ]
];

Session Container

There are 2 methods for instanting Session Manager.

Manual

<?php
use Zend\SessionContainer;
use Zend\Session\SessionManager;
$sessionManager = $container->get(SessionManager::class);
$sessionContainer = new Container('ContainerNamspace', $sessionManager);

Using Factory

<?php
return [
    'session_containers' => [
        'ContainerNamespace',
        'Container\Namespace',
        'container_namespace'
    ]
];

Some methods on Container

$containerNamespace->offsetGet('userId'); // return '1'
$containerNamespace->offsetSet('userId', 1); // set userId as 1
$containerNamespace->offsetExists('userId'); // return truel of false
$containerNamespace->offsetUnset('userId'); // unset the key 'userId'

Some methods on SessionManager

$sessionManager->getId(); // return the id of session.
$sessionManager->setId('517ac3'); // set id for session.
$sessionManager->regenerateId(true); // re-generate session id.
$sessionManager->rememberMe(60*60*30); // cookie store 30 days.
$sessionManager->forgetMe(); // delete the cookie.