ZF2在事件处理程序之间共享数据(附加)


ZF2 sharing data between event handlers (attach)

我正在尝试在zf2中的事件附件之间共享数据。

确切地说,我附属于missingTranslation,它是zf2翻译器的一部分。我需要在missingTranslation中捕获一些数据,然后在执行、Dispatch或Finish结束时,我将对数据进行一些验证,然后如果所有内容都经过验证,我将保存它。

attach('missingTranslation', function ($e){
    // some kind of storage with $e->getParam('message');
});
attach(MvcEvent::EVENT_DISPATCH, function (){
    // some validation, checks and mangling 
    file_put_content({the_storage});
});

我一直在研究缓存数据,但使用xcache或apc需要特殊的扩展,而服务器没有。

所以我的问题是我该怎么做?

您应该能够将信息和传入的Event一起传递给回调。像这个

$eventManager->attach(MvcEvent::EVENT_DISPATCH,function (MvcEvent $e) {
    $e->setParam('test', 10);
}, 200);
$eventManager->attach(MvcEvent::EVENT_DISPATCH,function (MvcEvent $e) {
   var_dump($e->getParam('test'));
}, 100);

这将在var_dump 上输出10

很抱歉等待。

我花了一些时间才注意到,当然,事件DISPATCH实际上是在事件missingTranslation之前运行的。

所以我用的不是DISPATCH而是FINISH

$this->translatorEventManager->attach('missingTranslation',function ($e) use (&$storage)
    {
        if ($this->config['string_length'] <= strlen($e->getParam('message'))
            || $this->config['string_length'] == -1
        ) {
            $backtrace = debug_backtrace();
            $ref = str_replace($this->config['zf_base_path'],
                    '',
                    $backtrace[10]['file']
                )
                . ':' . $backtrace[10]['line'];
            $storage[$e->getParam('locale')][] = array(
                'message_id'     => $e->getParam('message'),
                'message_string' => '',
                'domain'         => $e->getParam('domain'),
                'reference'      => $ref,
            );
        } else {
            // LOAD FROM DATABASE
        }
    });
    $this->appEventManager->attach(MvcEvent::EVENT_FINISH, function($e) use ($translator, &$storage) {
        $translator
            ->addTranslations($storage)
            ->save();
    });  

你们中的一些人可能会说这是一种非常糟糕的方法,因为众所周知debugbackup()会占用很多时间。它会把Bootstrap上的模块弄得一团糟。

为了使其正常运行,系统在后台运行一个外部curl命令,然后运行相同的页面,但使用参数"thread"。因此,即使运行整个模块需要1分钟,用户也不会注意到这一点