Zend framework2 设置布局变量以供ZF2中的(404)错误页使用

Zend framework2 设置布局变量以供ZF2中的(404)错误页使用,zend-framework2,Zend Framework2,目前,我使用BaseController的onDispatch方法设置了两个变量,以供应用程序的总体布局.phtml使用,我的所有其他控制器都扩展了该方法: public function onDispatch(MvcEvent $e) { $config = $this->getServiceLocator()->get('config'); $this->layout()->setVariable('platformName', $config['

目前,我使用BaseController的onDispatch方法设置了两个变量,以供应用程序的总体布局.phtml使用,我的所有其他控制器都扩展了该方法:

public function onDispatch(MvcEvent $e) 
{

    $config = $this->getServiceLocator()->get('config');
    $this->layout()->setVariable('platformName', $config['platform']['name']);
    $this->layout()->setVariable('platformYear', $config['platform']['year']);
}
这很好,直到我测试了一些错误页面,发现这些页面没有提供变量,因为它没有使用基本控制器


如何绕过此问题并为错误页面提供相同的变量?

更改您正在侦听的事件

在这种情况下,我将把这个逻辑移到应用程序引导事件或应用程序呈现事件(我还没有测试过这个,但它可能可以正常工作)

例如,在Module.php中

public function onBootstrap($e)
{
    $config = $e->getApplication()->getServiceManager()->get('config');
    //$e->getViewModel()->setVariable();
}
我还没有测试过这句话,但它会让你朝着正确的方向前进

编辑:找到了使用渲染事件的示例

public function onBootstrap($e)
{
    $event = $e->getApplication()->getEventManager();

    $event->attach('render', function($e) {
        $config = $e->getApplication()->getServiceManager()->get('config');
        $e->getViewModel()->setVariable('test', 'test');
    });
} 
(Necro)

在控制器中使用
onDispatch
时,请记住将事件和所有:

public function onDispatch(MvcEvent $e)
{
    // Your code
    return parent::onDispatch($e);
}
否则,该控制器中的操作逻辑将被忽略