Zend2:如何将布局中包含的视图渲染为变量?

时间:2013-01-23 13:59:35

标签: zend-framework2

我需要在变量中保存所有渲染的内容(布局+视图)以使用Zend_Cache保存它,我不能使用Varnish,nginx或其他软件来执行此操作。目前我这样做:

$view->setTemplate('application/index/index');
$viewContent = $renderer->render($view);
$view = $this->getEvent()->getViewModel();
$view->content = $viewContent;
$content = $renderer->render($view);

有谁能建议我更优雅的解决方案? Mb使用EventManager捕获原生渲染事件或使用Response对象或 dispatch 事件获取一些技巧?想听听所有建议。

谢谢!

1 个答案:

答案 0 :(得分:1)

为您的Module课程添加两个听众。如果匹配是缓存的,那么一个侦听器会在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
    }
}

只需确保在服务管理器中的cache-service下注册缓存实例即可。您可以更新上面的示例,以便在呈现事件期间检查路由是否在$routes数组中。现在,您只需检查缓存是否具有密钥,这可能比在in_array($route, $routes)事件期间执行render更慢。