whateverthing.com

Twig Tip: Configuring the Cache

It's no secret that I'm a fan of the Twig templating system. I like the syntax and flexibility far more than Smarty, PHP Templates, and other solutions I've worked with. I also like that it has minimal outside dependencies, so I can quickly add it to any project.

One of Twig's more interesting features is that it converts template files to PHP classes. This can really save processing power, because it only has to happen once and future references to that template can just invoke the saved PHP class.

However, if you forget to enable Twig caching, the compiled PHP classes are discarded after each page load - this burns a ton of resources and slows down your site.

Enabling Twig caching only requires a few magical incantations, and as luck would have it, I'm happy to demonstrate two common scenarios.

The TwigServiceProvider included with the Silex framework allows extra configuration to be passed by a "twig.options" array, like so:

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path'       => __DIR__ . '/views',
    'twig.options'    => array(
        'cache' => __DIR__ . '/cache',
    ),
));

Conversely, if you are manually defining the Twig service (as I do on a project that uses the Pimple dependency injection container), the options are passed as the second parameter of the Twig_Environment constructor:

$app['twig_loader'] = $app->share(function($app) {
    $twig = new Twig_Loader_Filesystem(__DIR__ . '/templates');

    return $twig;
});

$app['twig'] = $app->share(function($app) {
    $twig = new Twig_Environment($app['twig_loader'], array(
        'cache' => __DIR__ . '/cache',
    ));

    return $twig;
}

Note: It's important to remember that the cache folder needs to be writeable by the PHP process, otherwise your site could break. Also, when you deploy new code, you will either have to manually flush the cache (delete all files in it) or use a unique cache folder. I find it's easiest to deploy to release-specific folders and then store the cache underneath in a non-web-accessible location.

Once your cache is configured, make sure you enable APC or Zend OpCache to take full advantage of the cached templates - because the templates are now PHP classes, they can be opcode cached for maximum performance.

I'm working on a Silex book!

The book will cover the concepts, features, and philosophy of Silex, a PHP microframework. Other technologies and libraries (such as Twig and Imagine) will be explored as well.

Sign up & be notified when the book is published on LeanPub.

Sign Up

Published: February 17, 2015

Categories: coding

Tags: dev, development, coding, silex, opinion, howto, twig, cache, pimple