Refreshing single template twig cache in production
If you have a PHP application that handles dynamic Twig templates, which can be changed by a user, you have most likely already stumbled upon the question:
How can I delete the template cache in production, without flushing my entire cache?
I hope a search engine brought you here, because I have an answer, which I wasn’t able to find on Stackoverflow or anywhere else.
For some reason, Twig has no documentation about that issue and the ways to achieve it are rather hidden.
Using Twig cache and environment
Interacting with the cache directly and using the @internal Environment::getTemplateClass()
method feels more than just a little hacky:
$twigCache = $twig->getCache(false);
$twigCache->write(
$twigCache->generateKey($templateName, $twig->getTemplateClass($templateName)),
$twig->compileSource($twig->getLoader()->getSourceContext($templateName))
);
And the big question is really:
Why isn’t there a simple
Environment::refreshCache(string $templateName)
method?
Unfortunately I don’t have an answer. But I have another, even better solution …
Auto reloading your Twig template
After too much try & error, I started reading the twig source-code to find out how it is using the cache internally and stumbled upon a method that looked promising: Environment::enableAutoReload()
.
Obviously we don’t activate it blindly and cause a performance bottleneck in production, but we can utilize it to refresh our template. You know when your Twig template was changed and the cache needs to be reloaded, right? So at that moment you can do this:
$twig->enableAutoReload();
$twig->load('@bundle/' . basename($template->getFilename()));
$twig->disableAutoReload();
All you need to do is: pass in the correct filename (and possibly bundle identifier) used by your Twig loader.
Using this method of reloading the Twig template cache in production is working pretty well for me and I haven’t seen any side effects yet. But I haven’t used that approach on high traffic websites, so I can’t guarantee that there won’t be any race conditions.