Symfony2: HTTP Cache [part 1]


Ok, so Symfony has a cache layer which you can use to cache your responses. At first i was confused about why should i use this cache when i already could set Control-Cache headers on the responses. Then i did this little experiment to see what was the deal:

Open 2 diferent browsers and call a test page with it´s controller set like this:

class DefaultController extends Controller
{
    /**
     * @extra:Route("/", name="_base")
     */
    public function indexAction()
    {

        $response = new Response();
        $response->setMaxAge(10); //< 10 seconds! you can test this refreshing the page.
         $response->setPublic();

       return $this->render('SomeBundle:Default:index.html.twig', array('rand'=>rand()), $response); //this twig renders a random number to test that the response is actually cached.

    }
}

If you DONT use the AppCache, when you open the page in the 2 diferent browsers, you will see 2 diferent responses. Then the cache will be handled by the browser.

But if you DO use the AppCache, the 2 browsers will show the SAME response, the cache will still be handled by the browser, but using the initial cached data provided by the AppCache layer:

<?php
# app.php
//require_once __DIR__.'/../app/bootstrap.php.cache';
//require_once __DIR__.'/../app/AppKernel.php';
require_once __DIR__.'/../app/bootstrap_cache.php.cache';
require_once __DIR__.'/../app/AppCache.php';

use Symfony\Component\HttpFoundation\Request;

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

So in the above example, 100 users could ask for the same url ( inside the MaxAge timeframe of the response ) and all would get the SAME response, so the response would be generated only once. If you didnt used the cache layer, your app would have to generate 100 responses before using the cache from each user´s computer.

Keep reading more: HTTP Cache tutorial.

Advertisements