要在ApiPlatform提供程序的操作中添加缓存头,您可以使用Symfony HTTP Cache组件中的CacheControl类。您可以通过在操作注释中使用@Cache控制器注释来自定义缓存头。例如:
use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Component\Cache\CacheItem; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Contracts\Cache\CacheInterface; use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface; use ApiPlatform\Core\Bridge\Symfony\Validator\Validator;
/**
@Route("/api/posts")
@Cache(public=true, maxage="600", smaxage="600") */ class PostController { private $serializerContextBuilder; private $validator; private $cache;
public function __construct(SerializerContextBuilderInterface $serializerContextBuilder, Validator $validator, CacheInterface $cache) { $this->serializerContextBuilder = $serializerContextBuilder; $this->validator = $validator; $this->cache = $cache; }
/**
@Route("/", methods={"GET"})
@param Request $request
@return Response */ public function index(Request $request): Response { $item = $this->cache->getItem('api_posts'); if (!$item->isHit()) { $posts = ... $item->set($posts); $this->cache->save($item); }
return new Response($item->get(), 200, ['Content-Type' => 'application/json']); } }
在上面的示例中,我们在操作注释中添加了@Cache控制器注释,其中maxage和smaxage属性分别指定了缓存的最大年龄和共享缓存的最大年龄(如果存在)。在操作方法中,我们使用Symfony HTTP Cache组件中的CacheInterface将请求的结果缓存到文件系统中,然后将结果响应给客户端。