Zend Framework 2如何在ListenerAggregateInterface中触发MvcEvent

时间:2014-12-02 21:34:00

标签: triggers zend-framework2 listener

我想在我的侦听器中触发错误事件并发送自定义http状态代码(409) - 请参阅onEvent

我通过监听器配置

附加了我的听众
return [
'service_manager' => array(
    'invokables' => array(
        'SendFeedListener' => 'MyModule\Listener\SendFeedListener',
    ),
),
'listeners' => array(
    'SendFeedListener',
),
];

我的听众:

class SendFeedListener implements ListenerAggregateInterface, ServiceLocatorAwareInterface
{
use ServiceLocatorAwareTrait, ConfigAwareTrait;

/**
 * @var \Zend\Stdlib\CallbackHandler[]
 */
protected $listeners = [];

public function attach(EventManagerInterface $events)
{
    $sharedEvents = $events->getSharedManager();
    $this->listeners[] = $sharedEvents->attach(
        'MyModule\\Service\\MyService',
        '*', // listen for all events
        array($this, 'onEvent'),
        100
    );
}

...

public function onEvent(EventInterface $e)
{
   // ... some code

   // it went wrong, I want to trigger some error
   if($this->getMyService()->doSomething() == false) {
     $mvcEvent = $this->getServiceLocator()->get('application')->getMvcEvent();
     $this->getServiceLocator()->get('application')
     ->getEventManager()
     ->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $mvcEvent);
   }
 }
...
}

}

我可以做的事情如下:

// something went wrong
$sharedEvents = $e->getTarget()->getEventManager()->getSharedManager();
$sharedEvents->attach('Zend\\Mvc\\Application', MvcEvent::EVENT_RENDER,
            array($this, 'errorResponse'), -10000);

public function errorResponse($e)
{
    $response = $e->getResponse();
    $response->setStatusCode(409);
    $response->setContent((new JsonModel($this->error->toArray()))->serialize());
}

但它看起来很疯狂

1 个答案:

答案 0 :(得分:0)

试试这个:

$e->setError('my-custom-error');
$e->getTarget()->getEventManager()->trigger('dispatch.error', $e);

我不确定100%,但如果我没记错,你只能在dispatch.error期间和触发onRoute之前触发dispatch