【问题标题】:preDispatch doesn't work预调度不起作用
【发布时间】:2026-02-07 00:50:01
【问题描述】:

我有一点问题,我有控制器扩展 AbstractActionController,我需要在任何操作之前调用一些函数,例如 indexAction 我认为 preDispatch() 在任何操作之前调用但是当我在 $this->view- 中尝试此代码时>测试什么都不是。

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

【问题讨论】:

    标签: zend-framework2


    【解决方案1】:

    当我希望这样做时,我使用定义的onDispatch 方法:

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

    另外,请查看http://mwop.net/blog/2012-07-30-the-new-init.html 以获取有关如何在 ZF2 中使用调度事件的更多信息。

    【讨论】:

    • 感谢魔鬼,我在谷歌上找到了这个,我忘了在调度时给父母打电话......
    【解决方案2】:

    您最好在模块类上这样做,并使用 EventManager 来处理 mvc 事件,如下所示:

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

    【讨论】:

      【解决方案3】:

      在一行中:

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

      最后一个数字是重量。作为减等于发布事件。

      以下事件已预先配置:

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

      【讨论】: