Symfony:通过注释设置缓存头,只针对特定的状态码


Symfony: set cache headers through annotations only for specific status codes

是否有办法在symfony控制器注释中设置缓存头仅用于特定的状态码?

我目前正在这样做,就像下面的代码,利用由senoframeworkextrabundance提供的注释:

 /**
 * @Get("", name="product.list")
 * @Cache(public=true, maxage="432000", smaxage="432000")
 */
public function listAction()
{
    // ...
}

但是这个注释为所有响应设置缓存头,不管状态码是什么。我想设置缓存头仅为特定的状态码。

查看senoframeworkextrabundle中的代码,最直接的解决方案是不使用注释,而是在响应上手动设置缓存标头(例如在控制器或事件侦听器中),或者创建一个事件侦听器来阻止senoframeworkextrabundle设置缓存标头。

关于第二个选项,查看代码(https://github.com/sensiolabs/SensioFrameworkExtraBundle/blob/master/EventListener/HttpCacheListener.php#L86-L88),您可以在触发httpachelistener之前取消设置_cache请求属性。

<?php
use Symfony'Component'EventDispatcher'EventSubscriberInterface;
use Symfony'Component'HttpKernel'Event'FilterResponseEvent;
use Symfony'Component'HttpKernel'KernelEvents;
class MyCacheListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::RESPONSE => ['onKernelResponse', 16] // use a priority higher than the HttpCacheListener
        ];
    }
    public function onKernelResponse(FilterResponseEvent $event)
    {
        $request = $event->getRequest();
        $response = $event->getResponse();
        if (!$response->isSuccessful()) {
            $request->attributes->remove('_cache');
        }
    }
}

注册事件订阅者,例如在services.yml中:

services:
    my_cache_listener:
        class: MyCacheListener
        tags:
            - { name: kernel.event_subscriber }