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

时间:2013-08-13 14:04:04

标签: zend-framework2

目前我使用BaseController的onDispatch方法设置了应用程序整体layout.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']);
}

这很好用,直到我测试一些错误页面并发现这些页面没有提供变量,因为它没有使用基本控制器。

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

2 个答案:

答案 0 :(得分:2)

更改您正在收听的活动。

在这种情况下,我会将此逻辑移动到应用程序引导事件或应用程序呈现事件(我没有对此进行测试,但它可能会正常工作)。

一个例子,在你的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');
    });
} 

答案 1 :(得分:0)

(死灵)

在Controller中使用onDispatch时,请记住返回包含事件的父级和全部:

public function onDispatch(MvcEvent $e)
{
    // Your code
    return parent::onDispatch($e);
}

否则,将忽略该控制器中操作的逻辑。