ZF2 get global session container

11,113

Solution 1

Here's a more refined and improved version. It consists of the service "SessionService", a ViewHelper (which calls the SessionService), a ControllerPlugin (which also calls the SessionService), and shows how to set them up in the configuration file "module.config.php".

Make sure you set "use" paths or use absolute class paths in config.

SessionService.php:

class SessionService
{
    protected $sessionContainer;

    public function setSessionContainer(
        $sessionContainer
    ) {
        $this->sessionContainer = $sessionContainer;
    }

    public function __invoke() {
        return $this->sessionContainer;
    }
}

SessionHelper.php:

class SessionHelper extends \Zend\View\Helper\AbstractHelper
{
    protected $sessionService;

    public function setSessionService(
        $sessionService
    ) {
        $this->sessionService = $sessionService;
    }

    public function __invoke() {
        return $this->sessionService;
    }
}

SessionPlugin.php:

class SessionPlugin extends AbstractPlugin
{
    protected $sessionService;

    public function setSessionService(
        $sessionService
    ) {
        $this->sessionService = $sessionService;
    }

    public function __invoke() {
        return $this->sessionService;
    }
}

module.config.php:

'service_manager' => array(
    'factories' => array(
        'sessionService' => function(
            ServiceLocatorInterface $serviceLocator
        ) {
            $sessionContainer = new \Zend\Session\Container('base');
            $sessionService = new SessionService();
            $sessionService->setSessionContainer($sessionContainer);
            return $sessionService;
        },
    ),
),

'controller_plugins' => array(
    'factories' => array(
        'sessionPlugin' => function(
            AbstractPluginManager $pluginManager
        ) {
            $sessionService = $pluginManager->getServiceLocator()->get('sessionService');
            $sessionPlugin = new SessionPlugin();
            $sessionPlugin->setSessionService($sessionService);
            return $sessionPlugin;
        },
    ),
),

'view_helpers' => array(
    'factories' => array(
        'sessionHelper' => function (
            AbstractPluginManager $helperPluginManager
        ) {
            $sessionService = $helperPluginManager->getServiceLocator()->get('sessionService');
            $sessionHelper = new SessionHelper();
            $sessionHelper->setSessionService($sessionService);
            return $sessionHelper;
        },
    ),
),

Solution 2

In your Controller write:-

use Zend\Session\Container;

  1. Make Session variable

                   $user_session = new Container('user');
    

'user' is Your Session Name To put Value in Your Session write:

                $user_session->username = 'xyz';
  1. After Storing You can Access Your Session By:

                               $user_session->  username
    
  2. To destroy Session Variable Use:

     $session = new Container('user');
     $session->getManager()->getStorage()->clear('user');
    

    it is Just Like : -

    unset($_SESSION['user']); http://wownewcode.blogspot.in/2013/12/set-session-in-zend-framework-2.html

Share:
11,113

Related videos on Youtube

Oliver Konig
Author by

Oliver Konig

Updated on September 15, 2022

Comments

  • Oliver Konig
    Oliver Konig over 1 year

    I found how to get a session container like this: $session = new \Zend\Session\Container('base');

    But what if I need to access the session in many places during processing a HTTP request. Let's say in the Application module's indexAction in the IndexController, then I redirect it to the User\Controller\IndexController and need to access the session again, and then in a view helper or two, and who knows how often more.

    When constructing the session container every time anew, that is a waste of processing time. Yes, I debugged it to see what's going on in the constructor, and yes, there is some code executed behind the scenes. It is not as if the constructor would just return a global variable or something else which would be immutable and doesn't need a construction process.

    So what to do? Should I create a service for it? a controller plugin? a view helper? a service and a controller plugin and a view helper, with the latter calling the service?

    I'm sure it is something that many people must have come across and have dealt with, but I can't find any information on this.

    Any hint is dearly appreciated. Many thanks in advance! :-)

  • Oliver Konig
    Oliver Konig over 10 years
    but isn't that against the modular and object-oriented idea of the framework, to use global PHP variables?
  • Oliver Konig
    Oliver Konig over 10 years
    ...and then how do I refer to the session? How would I access the session variables? In your Authentication service example I can't see any reference to it, except how to set the storage strategy. How would you actually put and get session vars then?
  • netiul
    netiul over 10 years
    I guess so, yes. If you really want to do it properly then you've to inject the sessions variable in every class you need it. I agree it's nicer that way.
  • Oliver Konig
    Oliver Konig over 10 years
    Please read the first line of my question again. I know how to create session Container with "new Container('somename')", but I don't want to create a new Container every time I want to access the session data somewhere (e.g. when calling different functions which all need access to some session data), because the construction of a new Container involves a lot of code which would be executed multiple times unnecessarily, and that is exactly what I try to avoid.
  • Oliver Konig
    Oliver Konig over 10 years
    Injecting the same session variables in every class I need is not desirable for me, IMO it leads to convoluted and duplicated code.
  • netiul
    netiul over 10 years
    It doesn't lead to more convoluted code than it would with any another dependency imho. new Object(new Dep1(), new Dep2(), new Container('base')) (to prevent duplication, you could register reusable instances with a service manager).
  • Paul Kendal
    Paul Kendal almost 9 years
    Hi Konig. what instance of the AbstractPluginManager did you pass to the controller plugin. i tried passing 'Zend\Mvc\Controller\Plugin\AbstractPlugin' or the 'Zend\ServiceManager\AbstractPluginManager'. however with each of them i got this message:fatal error: Argument 1 must be an instance of AbstractPluginManager, instance of Zend\Mvc\Controller\PluginManager given config\module.config.php