Zend framework2 ZF2:如何将附加到MvcEvent::EVENT_FINISH的方法中的变量传递到附加在MvcEvent::EVENT_RENDER中的布局?

Zend framework2 ZF2:如何将附加到MvcEvent::EVENT_FINISH的方法中的变量传递到附加在MvcEvent::EVENT_RENDER中的布局?,zend-framework2,Zend Framework2,我试图理解Zend Framework 2 ZF2。几天前,我买了Slavey Karadzhov的《学习ZF2:以身作则》一书。现在我正在阅读它,并试图让一些例子起作用 我被困在第60页了。书中的例子很好用,但是我刚才做的修改不起作用。。。为什么?如何修复它 要进入相同的代码/情况,您必须: git clone https://github.com/slaff/learnzf2 . composer.phar self-update composer.phar install git st

我试图理解Zend Framework 2 ZF2。几天前,我买了Slavey Karadzhov的《学习ZF2:以身作则》一书。现在我正在阅读它,并试图让一些例子起作用

我被困在第60页了。书中的例子很好用,但是我刚才做的修改不起作用。。。为什么?如何修复它

要进入相同的代码/情况,您必须:

git clone https://github.com/slaff/learnzf2 .

composer.phar self-update
composer.phar install

git stash
git checkout 'ch-view'
之后,你将有相同的设置,我做。

现在,我更改了文件/module/Debug/view/Debug/layout/sidebar.phtml:

<h1>Top Line</h1>
<?= $this->content ?>

<h1>Bottom Line</h1>
public function getMvcDuration(MvcEvent $event)
    {
        // Here we get the service manager
        $serviceManager = $event->getApplication()->getServiceManager();
        // Get the already created instance of our timer service
        $timer = $serviceManager->get('timer');
        $duration = $timer->stop('mvc-execution');
        // and finally print the duration
        error_log("MVC Duration:".$duration." seconds");
    }
为此,在方法末尾添加了两行:

public function getMvcDuration(MvcEvent $event)
    {
        // Here we get the service manager
        $serviceManager = $event->getApplication()->getServiceManager();
        // Get the already created instance of our timer service
        $timer = $serviceManager->get('timer');
        $duration = $timer->stop('mvc-execution');
        // and finally print the duration
        error_log("MVC Duration:".$duration." seconds");

        $viewModel = $event->getViewModel();
        $viewModel->setVariable('mvcDuration', $duration);

    }
但是,这种更改不起作用,$duration的值不会传递给布局。问题是为什么?如何将$duration传递给布局的$this->mvc持续时间


p、 从官方github repo下载的代码表现得相当奇怪。。。更改项目文件,例如:/module/Debug/view/Debug/layout/sidebar.phtml不会更改输出。如果您在尝试帮助我处理此案例时遇到同样的情况,那么我建议您修改/vendor/learnzf2目录中的文件,而不是/module目录中的文件。我知道在供应商目录中修改代码不是一件好事,但让这篇文章只讨论一个问题。

好书。您的基本问题是,您试图在视图发送后触发的方法中将变量更新到视图中。您可能无法做到这一点,除非您重新定义触发它的事件,但这将破坏整个mvc持续时间计时的预期目的

尽管如此,您不应该从module.php向视图模型中注入变量。这很难测试。这就是视图帮助器的好处

public function getMvcDuration(MvcEvent $event)
    {
        // Here we get the service manager
        $serviceManager = $event->getApplication()->getServiceManager();
        // Get the already created instance of our timer service
        $timer = $serviceManager->get('timer');
        $duration = $timer->stop('mvc-execution');
        // and finally print the duration
        error_log("MVC Duration:".$duration." seconds");

        $viewModel = $event->getViewModel();
        $viewModel->setVariable('mvcDuration', $duration);

    }