Pregunta

I am trying to cache static content, I want this content is have a lifetime of one hour and the content is public, it is the same for everyone.

I have the following code in my controller:

$response = new Response();
$response->setPublic();
$response->setMaxAge(3600);
$response->setSharedMaxAge(3600);

if ($response->isNotModified($request)) {
   return $response;
}

return $this->render(
    'ThemesBundle:Ad:content.html.twig',
     array('context' => $context, 'block' => $block),
     $response
);

But the isNotModified() function always returns false.

PS: I am using Symfony 2.0.22

¿Fue útil?

Solución

You made a mistake, $response->isNotModified($request) is used only when using cache validation with a ETag or a Last-Modified test!

Here, you want to use expiration methods (with Cache-Control or Expires).

So just remove theses lines :

if ($response->isNotModified($request)) {
   return $response;
}

$response->setMaxAge(3600); (and setSharedMaxAge) alone will do the job, you don't need to test anything, the framework (or client navigator) will do it for you.

The same response will be served during 3600 second without passing by the action. After 3600 seconds, the user will pass by the action anew and it will be cached for 3600 seconds, etc.

In addition, you can use @Cache annotation which simplify the read ;)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top