What is the best way to go about getting sessions up and running in Zend Framework 2? I've tried setting session_start()
in my index.php file but then that gets run before any autoloaders have been bootstrapped, leading to incomplete objects sitting in my sessions.
In ZF1 you could have it initialize sessions by adding some options into the config, but I'm at a loss on how to do this in ZF2.
If i understand you correctly, all you wanna do is have your session working properly in your modules? Assuming that's correct there are two single steps.
1) Create the config: module.config.php
return array(
'session' => array(
'remember_me_seconds' => 2419200,
'use_cookies' => true,
'cookie_httponly' => true,
),
);
2) Start your Session: Module.php
use Zend\Session\Config\SessionConfig;
use Zend\Session\SessionManager;
use Zend\Session\Container;
use Zend\EventManager\EventInterface;
public function onBootstrap(EventInterface $evm)
{
$config = $evm->getApplication()
->getServiceManager()
->get('Configuration');
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config['session']);
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->start();
/**
* Optional: If you later want to use namespaces, you can already store the
* Manager in the shared (static) Container (=namespace) field
*/
Container::setDefaultManager($sessionManager);
}
Find more options in the documentation of \Zend\Session\Config\SessionConfig
If you want to store cookies too, then please see this Question. Credits to Andreas Linden for his initial answer - I'm simply copy pasting his.