无法在Zend Framework中的postDispatch()中设置视图变量

时间:2015-08-20 18:54:40

标签: php zend-framework plugins zend-view

我们有一个插件,它有一个postDispatch挂钩,用于记录使用ZF1开发的CMS上的使用情况统计信息。在生成其中一条记录之后,我们需要将它的唯一ID添加到视图中,以便能够通过AJAX请求更新它。

有几篇文章提供了不同的方法来设置postDispatch函数中的视图变量,但它们都没有为我们工作。他们都在preDispatch面团上工作。

gcc的方法1适用于preDispatch,但不适用于postDispatch。

$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
if (null === $viewRenderer->view) {
    $viewRenderer->initView();
}
$view = $viewRenderer->view;
$view->recordUID = XXXXXX

this answer

相同
Zend_Registry::set('recordUID', 'XXXXXX');

其他用户在别处建议(现在无法找到引用)使用method 2,这也适用于preDispatch但不适用于postDispatch

<form action="home.php">
  <input type="submit" value="Continue">
</form>

在调度请求后,视图对象似乎丢失了。

其他信息

  • 视图在Bootstrap.php(Zend's registry
  • 中初始化
  • 该插件已在public \ index.php
  • 中注册
  • 使用postDispatch函数
  • 注册统计信息的方法

1 个答案:

答案 0 :(得分:1)

当调用插件的postDispatch()方法时,视图已经被渲染。

我遇到了同样的问题,所以我将代码放入控制器的postDispatch()中(您还可以创建一个扩展Zend_Controller_Action的基本控制器,在那里覆盖preDispatch和postDispatch,让所有控制器扩展基本控制器)。 不要使用

$this->render('script'); 

在控制器内部,而是

$this->_helper->viewRenderer('script');

如果需要的话。

这里有一个答案link提供了解决方法:

class App_Plugin_MyPlugin extends Zend_Controller_Plugin_Abstract{

    public function preDispatch (Zend_Controller_Request_Abstract $request){
        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
        $viewRenderer->setNeverRender(true);
     }

     public function postDispatch(Zend_Controller_Request_Abstract $request){
       $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
       $view = $viewRenderer->view;
       $view->variable = 'new value';
       $viewRenderer->render();

     }
}
相关问题