mark winkle
mark winkle

Reputation: 206

Zend framework 2 session exists or not, in Module.php

I am trying to call the session in public function onBootstrap(MvcEvent $e) function in Module.php

public function onBootstrap(MvcEvent $e)
    {
    if( $user_session->offsetExists('user_email_id')){
       //code here
     } 
    else {

            header("Location: ". $this->serverUrl() . "/register");


        }

}

How can i achieve this?
i am not getting the echo $this->serverUrl(); inside the OnBootstrap function

Upvotes: 0

Views: 552

Answers (1)

AlexP
AlexP

Reputation: 9857

There a number of problems with this code.

  • You need to create a new session container (Zend\Session\Container) to set/get your session data.

  • You are trying to set headers manually, although this would work, there are better ways to do so in ZF2.

  • Redirection in the onBootstrap method is probably not the best 'time' to do so.

  • You attempt to use a view helper in Module.php (\Zend\View\Helper\ServiceUrl) to redirect. View helpers can should only be called in the view. You can use them, however you would need to fetch it via the ViewPluginManager, rather than using $this->.

With these points in mind I would consider adding a event listener either late onRoute or early onDispatch.

For example:

namespace FooModule;

use Zend\ModuleManager\Feature\BootstrapListenerInterface;
use Zend\EventManager\EventInterface;
use Zend\Session\Container;
use Zend\Mvc\MvcEvent;

class Module implements BootstrapListenerInterface
{
    public function onBootstrap(EventInterface $event)
    {
        $application  = $event->getApplication();
        $eventManager = $application->getEventManager();

        $eventManager->attach(MvcEvent::EVENT_DISPATCH, [$this, 'isLoggedIn'], 100);
    }

    public function isLoggedIn(MvcEvent $event)
    {
        $data = new Container('user');

        if (! isset($data['user_email_id'])) {

            $serviceManager = $event->getApplication()->getServiceManager();
            $controllerPluginManager = $serviceManager->get('ControllerPluginManager');

            // Get the \Zend\Mvc\Controller\Plugin\Redirect
            $redirect = $controllerPluginManager->get('redirect');

            return $redirect->toRoute('some/route/path', ['foo' => 'bar']);
        }
        // use $data here
    }
}

Upvotes: 1

Related Questions