user1499668
user1499668

Reputation: 51

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;
 }
}

Upvotes: 5

Views: 7260

Answers (3)

superhero
superhero

Reputation: 6482

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.

Upvotes: 13

Michael Ben-Nes
Michael Ben-Nes

Reputation: 7645

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';

Upvotes: 2

AlloVince
AlloVince

Reputation: 1655

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
  }
}

Upvotes: 6

Related Questions