我有一个 Controller ,其操作在 Twig 中呈现
{{ render_esi(controller('MyWebsiteBundle:Element:header')) }}
操作本身如下所示:
/**
* @return Response
*/
public function headerAction()
{
$currentLocale = $this->getCurrentLocale();
$response = $this->render('MyWebsiteBundle:Element:header.html.twig', array(
'currentLocale' => $currentLocale,
'myTime' => time()
));
$response->setPublic();
$response->setSharedMaxAge(3600);
return $response;
}
当我重新加载浏览器时,“myTime”
每次都会改变。
如何使用setShardeMaxAge()
,以便仅在 MaxAge 过期后渲染 Twig?
最佳答案
在 Symfony2 中,您需要执行一些操作才能激活 esi 缓存。
1) 在 app/config/config.yml
中确保您激活了 esi,并带有片段路径。
framework:
esi: { enabled: true }
fragments: { path: /_proxy }
2) 用AppCache对象包装内核
// web/app.php
$kernel = new AppCache($kernel);
3) 设置AppCache配置
// app/AppCache.php
use Symfony\Bundle\FrameworkBundle\HttpCache\HttpCache;
class AppCache extends HttpCache
{
protected function getOptions()
{
return array(
'debug' => false,
'default_ttl' => 0,
'private_headers' => array('Authorization', 'Cookie'),
'allow_reload' => false,
'allow_revalidate' => false,
'stale_while_revalidate' => 2,
'stale_if_error' => 60,
);
}
}
关于您的问题,如果它正在缓存您的响应,唯一的问题是它会在您每次刷新页面时重新加载。确保配置 allow_reload
属性设置为 false。
您可以在这里阅读更多相关信息: http://symfony.com/doc/current/book/http_cache.html
关于Symfony2 : ESI setMaxAge Cache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30614573/