我自己触发zf2调度事件?

时间:2014-06-05 11:01:19

标签: events zend-framework2 dispatch

为什么在我的控制器中触发调度事件后会触发?

onBootstrap:

$sharedManager->attach('*', '*', function($e) {
    Debug::dump($e->getName());
});

的indexAction:

$this->getEventManager()->trigger(__FUNCTION__ . '.pre', $this);
Debug::dump('indexAction do...');
$this->getEventManager()->trigger(__FUNCTION__ . '.post', $this);

结果是:

string(5) "route"
string(15) "indexAction.pre"
string(17) "indexAction do..."
string(16) "indexAction.post"
string(8) "dispatch"
string(8) "dispatch"
string(6) "render"
string(8) "renderer"
string(13) "renderer.post"
string(8) "renderer"
string(13) "renderer.post"
string(8) "response"
string(6) "finish"
string(12) "sendResponse"

我找到了调度过程: https://docs.google.com/drawings/d/1OwFfjgaiXDuKmS2I8nnJNFqoDgEWNNB-_-tUXUPVrgQ/edit 但似乎这不正确

我认为调度事件将作为dispatch.pre触发,而不是dispatch.post ...

1 个答案:

答案 0 :(得分:0)

您的调试方法会给您带来奇怪的结果。

添加'调试监听器'使用默认事件优先级(1)事件名称的输出实际上在发生调度事件后发生。

这是因为ZF2首先注册控制器的dispatch事件(事件优先级为1)。因此事件以正确的顺序发生;它只是你的听众输出在错误的时间。

您可以通过向Zend\EventManager\EventManager::trigger()

添加一行来测试事件的顺序
// Zend\EventManager\EventManager
public function trigger($event, $target = null, $argv = array(), $callback = null)
{
    echo '<br>Triggered: ' . $event;
    //...
}

此输出(不包括模块自举位)

Triggered: bootstrap
Triggered: route
Triggered: dispatch // MVC dispatch
Triggered: dispatch // Action Controller disaptch
Triggered: foo.pre  // Controller custom events
Triggered: foo.post // Controller custom events
Triggered: render
Triggered: renderer
Triggered: renderer.post
Triggered: renderer
Triggered: renderer.post
Triggered: response
Triggered: finish