문제

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

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top