Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preDispatch doesn't work

I have little problem, I have controller extends AbstractActionController, and i need call some function before any action, for example indexAction i think preDispatch() is call before any action but when i try this code in $this->view->test is nothing.

class TaskController extends AbstractActionController
{
 private $view;

 public function preDispatch()
 {
   $this->view->test = "test";
 }

 public function __construct()
 {
   $this->view = new ViewModel();
 }

 public function indexAction()
 {
   return $this->view;
 }
}
like image 666
user1499668 Avatar asked Jul 03 '12 18:07

user1499668


3 Answers

When I wish to do this I use the defined onDispatch method:

class TaskController extends AbstractActionController
{
  private $view;

  public function onDispatch( \Zend\Mvc\MvcEvent $e )
  {
    $this->view->test = "test";

    return parent::onDispatch( $e );
  }

  public function __construct()
  {
    $this->view = new ViewModel();
  }

  public function indexAction()
  {
    return $this->view;
  }
}

Also, have a look at http://mwop.net/blog/2012-07-30-the-new-init.html for additional information about how to work with the dispatch event in ZF2.

like image 149
superhero Avatar answered Nov 08 '22 07:11

superhero


You'd better do this on module class, and use EventManager to handler the mvc event like this:

class Module
{
  public function onBootstrap( $e )
  {
    $eventManager = $e->getApplication()->getEventManager();
    $eventManager->attach( \Zend\Mvc\MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 100 );
  }

  public function preDispatch()
  {
    //do something
  }
}
like image 34
AlloVince Avatar answered Nov 08 '22 07:11

AlloVince


And in one line:

public function onBootstrap(Event $e)
{
  $e->getTarget()->getEventManager()->attach('dispatch', array($this, 'someFunction'), 100);
}

The last number is weight. As minus equal post event.

The following event are preconfigured:

const EVENT_BOOTSTRAP      = 'bootstrap';
const EVENT_DISPATCH       = 'dispatch';
const EVENT_DISPATCH_ERROR = 'dispatch.error';
const EVENT_FINISH         = 'finish';
const EVENT_RENDER         = 'render';
const EVENT_ROUTE          = 'route';
like image 34
michaelbn Avatar answered Nov 08 '22 07:11

michaelbn