0

Full page caching with Symfony2 and the Symfony2 reverse proxy

Activate the cache in web/app.php

require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
require_once __DIR__.'/../app/AppCache.php';

use Symfony\Component\HttpFoundation\Request;

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$kernel = new AppCache($kernel);
$kernel->handle(Request::createFromGlobals())->send();

After that, go to your controller action. At first, you will need to create a new Response object. After that set it as public so the cached response is used by all visitors. Then you will need an unique identifier, the etag, for the cache – an id and a modified date of the resource for example. If the resource is not modified the cached response will be responded. If the resource was modified since the last cache got created, a new cached response will be created with the new eTag. See the example:

public function detailAction($id) {

        $response = new Response();
        $response->setPublic();

        $em = $this->get('doctrine')->getEntityManager();
 
        $article = //get article by id from repository
  
        $identifier = md5(
                        $article->getId().
                        $article->getUpdatedAt()->format('Y-m-d H:i:s')
                      )

        $response->setETag($identifier );

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

        //do the heavy work 

        return $this->render(
            'MyAwesomeBundle:Board:detail.html.twig',
            array('awesomeObject' => $awesomeObject),
            $response
        );
    }
?>

Important: The Symfony2 reverse proxy is cool – but not that fast as reverse proxies written in c. If you want to build a website with a very high load, please consider using Varnish with Symfony2 for example.

Michi

Passion for sports with boards, climbing, mountain biking, traveling, photography, videography and software engineering. /n/n Heilbronn // Germany

Leave a Reply

Your email address will not be published. Required fields are marked *