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;
}
}
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.
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
}
}
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With