Custom Caching for Twig

In Superdesk Publisher we have implemented Mutlitenancy with possibility to have multiple themes (but one activated). To make process of switching, uploading and updating themes for tenant we had to came up with solution to clear cache only for one particular theme not the whole instance (with many organisations and tenants).

To achieve that we created custom Twig Cache class. It’s possible thanks Fabien Potencier change to Twig 1.22 (https://github.com/twigphp/Twig/pull/1812).

Our implementations puts template cache into %kernel.cache_dir%/twig/{tenant}/themes/{theme} directory (so it’s easy to remove it when needed).

Here is the code:

Let’s put it as a service:

Now we need to enable it. To do that in Symfony we need to create Compiler Pass.

Notice that we set TenantAware cache to twig only in production env.

As you can see — you can keep that cache anywhere you need (jusy pass redis or memcached services to cache class and override write and load methods)— but keeping it in filesystem gives you php opcache support.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store