Zend Framework 3: Sessions
$_SESSION
?Zend provided a wrapper around PHP Session, it takes some pros:
php composer.phar require zendframework/zend-session
<?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
]
];
There are 2 methods for instanting Session Manager.
<?php
use Zend\SessionContainer;
use Zend\Session\SessionManager;
$sessionManager = $container->get(SessionManager::class);
$sessionContainer = new Container('ContainerNamspace', $sessionManager);
<?php
return [
'session_containers' => [
'ContainerNamespace',
'Container\Namespace',
'container_namespace'
]
];
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'
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.