【问题标题】:Logic before "dispatch"-event“调度”事件之前的逻辑
【发布时间】:2013-06-06 17:01:07
【问题描述】:

我想在 MvcEvent::EVENT_DISPATCH 之前做一些逻辑,但是如果我将优先级设置为 1 以上,则 MvcEvent::getTarget() 函数返回 Mvc\Application 的对象而不是 Controller:

$e->getApplication()->getEventManager()->attach(MvcEvent::EVENT_DISPATCH, array($this, 'routing'), 100);

如果我将优先级设置为负值,我会得到 Controller 对象,但它会在 action-function 之后触发。在这种情况下如何获取 Controller 对象?

【问题讨论】:

  • 调度阶段是创建控制器并在其上调用操作的地方。如果你在它之前做某事,那么就没有控制器......你在它已经完成之后做某事。

标签: php model-view-controller zend-framework2


【解决方案1】:

您可以使用MvcEvent::getRouteMatch() 来确定将分派哪个控制器(如果有),或者通过覆盖AbstractActionController:setEventManager() 附加到控制器本身内部的控制器事件管理器。

即:

// in your controller

public function setEventManager(EventManagerInterface $events)
{
    parent::setEventManager($events);

    $events->attach(MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 100);
}

public function preDispatch(MvcEvent $event)
{
    // your custom logic here
}

【讨论】:

    【解决方案2】:
    // in your Module
    public function onBootstrap(MvcEvent $e)
    {
        $e->getApplication()
          ->getEventManager()
          ->getSharedManager()
          ->attach(
                'Zend\Stdlib\DispatchableInterface', 
                MvcEvent::EVENT_DISPATCH, array($this, 'onDispatch'), 
                2
            );
    }
    
    public function onDispatch(MvcEvent $a)
    {
        $target = $a->getTarget();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-07
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      • 2021-05-08
      • 2012-06-13
      • 1970-01-01
      • 2015-12-15
      相关资源
      最近更新 更多