Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Zend framework2 Zend2:如何将包装在布局中的视图渲染为变量?_Zend Framework2 - Fatal编程技术网

Zend framework2 Zend2:如何将包装在布局中的视图渲染为变量?

Zend framework2 Zend2:如何将包装在布局中的视图渲染为变量?,zend-framework2,Zend Framework2,我需要将所有呈现的内容(布局+视图)保存在一个变量中,以使用Zend_缓存进行保存,我不能使用Varnish、nginx或其他软件进行保存。目前我是这样做的: $view->setTemplate('application/index/index'); $viewContent = $renderer->render($view); $view = $this->getEvent()->getViewModel(); $view->content = $viewCo

我需要将所有呈现的内容(布局+视图)保存在一个变量中,以使用Zend_缓存进行保存,我不能使用Varnish、nginx或其他软件进行保存。目前我是这样做的:

$view->setTemplate('application/index/index');
$viewContent = $renderer->render($view);
$view = $this->getEvent()->getViewModel();
$view->content = $viewContent;
$content = $renderer->render($view);
有人能给我推荐更优雅的解决方案吗?Mb使用EventManager捕获本机渲染事件,或者使用响应对象或调度事件捕获一些技巧?我想听听所有的建议


谢谢

模块
类添加两个侦听器。一个侦听器在
route
之后提前检查匹配是否已缓存。第二个侦听器等待
render
,并获取输出以将其存储在缓存中:

namespace MyModule;

use Zend\Mvc\MvcEvent;

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        // A list of routes to be cached
        $routes = array('foo/bar', 'foo/baz');

        $app = $e->getApplication();
        $em  = $app->getEventManager();
        $sm  = $app->getServiceManager();

        $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($sm) {
            $route = $e->getRouteMatch()->getMatchedRouteName();
            $cache = $sm->get('cache-service');
            $key   = 'route-cache-' . $route;

            if ($cache->hasItem($key)) {
                // Handle response
                $content  = $cache->getItem($key);

                $response = $e->getResponse();
                $response->setContent($content);

                return $response;
            }
        }, -1000); // Low, then routing has happened

        $em->attach(MvcEvent::EVENT_RENDER, function($e) use ($sm, $routes) {
            $route = $e->getRouteMatch()->getMatchedRouteName();
            if (!in_array($route, $routes)) {
                return;
            }

            $response = $e->getResponse();
            $content  = $response->getContent();

            $cache = $sm->get('cache-service');
            $key   = 'route-cache-' . $route;
            $cache->setItem($key, $content);
        }, -1000); // Late, then rendering has happened
    }
}
只需确保在服务管理器的
缓存服务
下注册缓存实例。您可以更新上面的示例,以在渲染事件期间检查路由是否位于
$routes
数组中。现在您只需检查缓存是否有密钥,这可能比在
render
事件期间在_array($route,$routes)中执行
要慢