Search code examples
variableszend-frameworklayoutcontrollerstore

Global data storage in Zend Framework 2


I would like to store data, eg. user name and surname to display them in many layouts. I want to set some variable in one controller and use it in layout.

Any solutions?

I created some similar layouts where i put:

<span id="STATUS">LOGGED: <span id="USERNAME"><?php echo $this->name. ' ' . $this->surname; ?></span>

But firstly, in some action of controller I get name and surname from database:

$db = $this->getServiceLocator()->get('MyDatabase'); $sql = 'SELECT * FROM Users'; $statement = $db->query($sql);/ $result = $statement->execute();

Then i set static variables in controller:

self::$name = $result['name']; self::$surname = $result['surname'];

Next in actions i change layout and pass variables to it:

$this->layout('layout/student'); $this->layout()->name = self::$name; $this->layout()->surname = self::$surname;

But I do not want get data from database in every controllers and pass variables in each of actions.


Solution

  • Okay my solution is this.

    Inside your module.php

    public function onBootstrap(MvcEvent $e)
    {
    
        $sharedEvents = $e->getApplication()->getEventManager()->getSharedManager();
        $sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
        //This event will only be fired when an ActionController under the MyModule namespace is dispatched.
        $controller = $e->getTarget();
    
        //to be able to view actions and controllers
        $params = $e->getApplication()->getMvcEvent()->getRouteMatch()->getParams();
        $nameSurnameArray = $controller->getServiceLocator()->get('NAMEOFTABLEWITHSQL')->getNameSurname();
            if($params['action'] == 'test'){
    
            $controller->layout('layout/testlayout');
            $controller->layout()->name = $nameSurnameArray['name'];
            $controller->layout()->surname = $nameSurnameArray['surname']';
            }
    
        }, 100);
    
        $eventManager        = $e->getApplication()->getEventManager();
        $serviceManager      = $e->getApplication()->getServiceManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
        $this->bootstrapSession($e);
    }
    

    So if the route is the Action test then testLayout is loaded and i pass to that layout the name and surname i got from database. Similarly you can specify a controller ($params['controller'] == 'testModule\Controller\testController') instead of an action if you have the same layout for one controller.

    This solution can be improved i guess but hopefully it will point you to the right direction