2012-07-03 9 views
6

Tengo un pequeño problema, tengo el controlador extiende AbstractActionController, y necesito llamar a alguna función antes de cualquier acción, por ejemplo indexAction creo que preDispatch() es llamada antes de cualquier acción, pero cuando pruebo este código en $ this-> view-> test no es nada.preDispatch no funciona

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

Respuesta

7

Será mejor que hace esto en la clase de módulo y utiliza EventManager al controlador del evento MVC así:

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

Y en una línea:

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

El el último número es el peso Como menos igual evento posterior.

El siguiente evento están preconfiguradas:

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

Cuando desee hacer esto utilizo el onDispatch método definido:

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

También, echar un vistazo a http://mwop.net/blog/2012-07-30-the-new-init.html para obtener información adicional acerca de cómo trabajar con el evento de envío en ZF2.

+1

gracias diablo, encontré esto en google, me olvidé de llamar al padre en el despacho ... – Ismael