ZF2 SessionManager usage
php, zend-framework2
Solution
There is not well documented SessionManagerFactory (zf2 api doc) and SessionConfigFactory (zf2 api doc). With those is instantiate SessionManager very easy, just put these factories to your ServiceManager configuration:
'service_manager' => [
'factories' => [
'Zend\Session\SessionManager' => 'Zend\Session\Service\SessionManagerFactory',
'Zend\Session\Config\ConfigInterface' => 'Zend\Session\Service\SessionConfigFactory',
],
],
and to module configuration put your session options, under the session_config key:
'session_config' => [
'remember_me_seconds' => 2419200,
'use_cookies' => true,
'cookie_httponly' => true,
],
and that's it, now you can grab SessionManager from service locator anywhere, for example in controller:
/** @var Zend\Session\SessionManager $sm */
$sessionManager = $this->serviceLocator->get('Zend\Session\SessionManager');
This is available as of 2.2 version of Zend Framework (related pull request).
Problem
I am new to ZF2 and not quite used to how to do stuff. I want to use session to keep track of an user (remember me). I had this code in one part of my class: ``` $sessionManager = new \Zend\Session\SessionManager(); $sessionManager->rememberMe($time); // i want to keep track of my user id too $populateStorage = array('user_id' => $user->getId()); $storage = new ArrayStorage($populateStorage); $sessionManager->setStorage($storage); ``` Ok, so far so good. When i try: ``` var_dump($sessionManager->getStorage()); ``` I get the expected data. In another part of my program, i want to retreive my data again (a bit like containers): ``` $sessionManager = new \Zend\Session\SessionManager(); var_dump($sessionManager->getStorage()); ``` This only returns an empty object. I guess this is due to the "new" and i think i have to implement SessionManager in a different way, but how? I do not know. This is what i came up with: In my Module i now have: ``` public function onBootstrap(\Zend\Mvc\MvcEvent $e) { $config = $e->getApplication() ->getServiceManager() ->get('Configuration'); $sessionConfig = new SessionConfig(); $sessionConfig->setOptions($config['session']); $sessionManager = new SessionManager($sessionConfig); $sessionManager->start(); ``` In my module.config: ``` 'session' => array( 'remember_me_seconds' => 2419200, 'use_cookies' => true, 'cookie_httponly' => true, ), ``` But how to procede? How do i get the instance for my sessionManager?