Silex and the HTTP_CACHE

The HTTP_CACHE resp. the reverse proxy of Symfony is a pretty cool thing.
And as it is build-in Silex it can speed up the already fast micro framework massivly,
wich is good for me, as i am mainly workin with Silex right now.

To enable it you have to register it first like its shown in the docs:

 $app->register(new Silex\Provider\HttpCacheServiceProvider(), array(
 'http_cache.cache_dir' => __DIR__.'/cache/',
 ));

Also provide the writable cache dir.

Then you have to return the Response Object with HTTP cache headers.

$app->get('/about', function () use ($app) {
 $body = $app['twig']->render('about.twig');
 return new Response($body, 200, array('Cache-Control' => 's-maxage=3600, public'));
 });

And its good practice to finally call it with a dev switch.

if ($app['debug']) {
 $app->run();
 }
 else{
 $app['http_cache']->run();
 }

Now in production environment the page will be cached and if it gets requested it will be served from the cache, if the cached version is not older then the time-to-live limit given in seconds by s-maxage.
So here you avoid expensive calculation time.
You could also provide a max-age directive to tell the client to cache it on clientside, to avoid the HTTP Request.
But as always with caches its quite a rodeo to balance performance and up-to-dateness.
Expiration and Validation Headers can of course be used aswell to controll the cache even more.

To illustrate the performance increase i loaded a simple about-page, which actually does nothing more then render a template.
So while warming the cache it needed 606ms and from the cache it reduced to 190ms.
warm cache:

from cache:

I cant tell how representative this is, but it aswell feels much faster, especially if you got more logic behind the page, like webservice calls etc.

BTW my superleansilexplate got also updated to support the Cache.

7 Replies to “Silex and the HTTP_CACHE”

  1. Christian, yes i was wondering about that also.
    But I guess to achieve this a Validation Header and the clientside Cache Header must be set.
    F.e. max-age=600 and ETag or Last-Modified.

    I did not yet because in my app i had no way to set a correct value to Last-Modified without too much calculation.
    Afaiu this still has to be done by hand.
    if not please correct me.

  2. $response = new Response($content->data, 200, array(
    		    'Cache-Control' => 's-maxage=120',
                'ETag' => uniqid()
    	));
    

    will solve the “304 Not Modified” issue. –Clear your cache before run with this code–

  3. How would you implement it in the response object if you’re returning a twig template like so:

    return $app['twig']->render('result.html.twig');
    

    I have twig cache activated but as the doc says it only put in cache the twig compilation, therefore I’d also like to make use of the HTTP Cache

Comments are closed.