我需要在变量中保存所有渲染的内容(布局+视图)以使用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 事件获取一些技巧?想听听所有建议。
谢谢!
答案 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
更慢。