Symfony:仅针对特定状态代码通过注释设置缓存 headers

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

有没有办法在 symfony 控制器注释中仅针对特定状态代码设置缓存 headers?

我目前正在像下面的代码一样使用 SensioFrameworkExtraBundle 提供的注释:

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

但是此注释为所有响应设置缓存 headers,无论状态代码是什么。我想为特定状态代码设置缓存 headers。

查看 SensioFrameworkExtraBundle 中的代码,最 straight-forward 的解决方案是不使用注释,而是在响应上手动设置缓存 headers(例如在控制器或事件侦听器中) ), 或者创建一个事件监听器来阻止 SensioFrameworkExtraBundle 设置缓存 headers.

关于第二个选项,查看代码 (https://github.com/sensiolabs/SensioFrameworkExtraBundle/blob/master/EventListener/HttpCacheListener.php#L86-L88),您可以在触发 HttpCacheListener 之前取消设置 _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 }