Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Bootstrap Sessions in Zend Framework 2

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.

like image 756
dragonmantank Avatar asked Oct 08 '12 03:10

dragonmantank


1 Answers

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.

like image 78
Sam Avatar answered Nov 08 '22 22:11

Sam