2

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

COil
  • 7,201
  • 2
  • 50
  • 98

1 Answers1

2

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 ;)

Carrie Kendall
  • 11,124
  • 5
  • 61
  • 81
Sybio
  • 8,565
  • 3
  • 44
  • 53
  • OK, I get it now. I was confused because 1) I was expecting a 304 which it not the case. 2) When hitting "enter" in the URL bar with Chrome the cache is invalidated ! When accessing the page normally through the application menu the cache works as expected. I can't use the annotation syntax because the caching time is dynamic. Thanks for your help, that's clear now. :) – COil Jun 14 '13 at 12:35