I'm intrigued by this snippet:
public function indexAction()
{
$response = $this->render('MyBundle:Main:index.html.twig');
$response->setETag(md5($response->getContent()));
$response->isNotModified($this->getRequest());
return $response;
}
Should I do this whenever possible? I'm thinking that most pages in my websites could save bandwidth this way (though not CPU).
The If-Modified-Since request HTTP header makes the request conditional: the server sends back the requested resource, with a 200 status, only if it has been last modified after the given date.
The HTTP 304 Not Modified client redirection response code indicates that there is no need to retransmit the requested resources. It is an implicit redirection to a cached resource.
The If-Modified-Since HTTP header indicates the time for which a browser first downloaded a resource from the server. This helps determine whether or not the resource has changed since the last time it was accessed.
The HTTP status code 304 means Not Modified – the web page you requested hasn't changed since the last time you accessed it. After that, your browser will retrieve the cached version of the web page in your local storage.
Doing this blindly just to save Bandwidth is in my opinion a waste of time and an unnecessary code complexification.
Your cache strategy is very important and must be implemented wisely on your whole application, using various cache techniques depending on what your controllers do.
For static pages, I would recommend to use cache expiration without Etag but more with Expires Header or Cache-control Header
For dynamic pages, I would recommend here a use of cache with more validation and then the use of Last-modified of Etag
Lastly, for many cases (in my case, static pages with heavy shared caching but a topbar on top with personal info about logged user that I cannot cache), I'll recommend the use of ESI to cache separately the different blocks of your page (in my case, topbar never cached, and the rest of the page cached with validation and ETag)
This way, with a little bit more reflexion and global strategy, you define on top of your application a reliable and efficient caching that saves both your bandwith and your CPU
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With