gpt4 book ai didi

symfony - 没有带注释的缓存头

转载 作者:行者123 更新时间:2023-12-04 13:32:51 25 4
gpt4 key购买 nike

为了在 Controller 中没有缓存的情况下设置响应,您可以执行以下操作:

$response = new Response();
$result = $this->renderView(
'AcmeDemoBundle:Default:index.html.twig',
array('products' => $products, 'form' => $form->createView()));
$response->headers->addCacheControlDirective('no-cache', true);
$response->headers->addCacheControlDirective('max-age', 0);
$response->headers->addCacheControlDirective('must-revalidate', true);
$response->headers->addCacheControlDirective('no-store', true);
$response->setContent($result);

return $response;

但是,使用注释来确保每种方法都具有相同的结果,该怎么办?

我尝试这样做,但是继续保存缓存,如果使用浏览器的“后退”按钮,则保留缓存:
/**
* @Cache(maxage="0", vary="no-cache, must-revalidate, no-store", smaxage="0", expires="now", public="false")
*/
class DefaultController extends Controller
{
/**
* Homepage: show products
*
* @Route("/", name="homepage")
* @Template
*/
public function indexAction()
{
$sessionCart = $this->get('demo');
$filters = $sessionCart->getFilters($this->getDoctrine()->getEntityManager());
$products = $this->getDoctrine()->getRepository('AcmeDemoBundle:Product')->search($filters);
$form = $this->createForm(new FilterType, $filters);

return array('products' => $products, 'form' => $form->createView());
}

如果按照文档所述进行强加:
@Cache(vary=["no-cache", "must-revalidate", "no-store"]...

给了我一个语法错误,它不期望“[”,所以我尝试了如上所述。

最佳答案

您正在混合两件事。在第一个代码段中,您将设置缓存控制 header ,但是要使用批注设置Vary header 。但是VaryCache-Control头应该站立的no-cache, must-revalidate, no-store header 完全不同。 Vary表示响应可以在哪个方面考虑请求(即Cookies)。请参阅以下答案以了解:https://stackoverflow.com/a/1975677/2084176
在您的情况下(无缓存),如果不存在缓存头,则可以依靠symfony设置的on the defaults:

Symfony2 automatically sets a sensible and conservative Cache-Control header when none is set by the developer by following these rules:

  • If no cache header is defined (Cache-Control, Expires, ETag or Last-Modified), Cache-Control is set to no-cache, meaning that the response will not be cached;

编辑:如果您需要为每个 Controller 操作设置缓存头,则可以使用 kernel.response 事件。创建一个对此事件使用react的监听器,并使用适当的缓存控制来修改响应。
namespace Acme\DemoBundle\EventListener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class AcmeCacheListener
{
public function onKernelResponse(FilterResponseEvent $event)
{
$response = $event->getResponse();

$response->headers->addCacheControlDirective('no-cache', true);
$response->headers->addCacheControlDirective('max-age', 0);
$response->headers->addCacheControlDirective('must-revalidate', true);
$response->headers->addCacheControlDirective('no-store', true);
}
}
并在你的 services.yml
services:
kernel.listener.your_listener_name:
class: Acme\DemoBundle\EventListener\AcmeCacheListener
tags:
- { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }

关于symfony - 没有带注释的缓存头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17732454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com