Invalidate Symfony cache on multiple servers using SonataCacheBundle (English)


  symfony    english    cache 

When working on high trafic websites or, in my personal case, working on multilanguage websites, this is sometime necessary to invalidate the Symfony application cache on multiple servers.

Recently, I've worked on a pull request on the SonataCacheBundle Symfony bundle in order to add a new adapter that will allow you to clear all or part of Symfony cache in Symfony: a SymfonyAdapter.

My initial need was to invalidate all translations cache on all servers where the application is deployed and this when users modify a translation in the back office.

Technically, this means clearing the "app/cache//translations" directory on all servers and this is done very easily using SonataCacheBundle.


Start by adding a new dependency in your composer.json file:

"sonata-project/cache-bundle": "dev-master"

then, install it:

$ composer install

After registering this bundle in your app/AppKernel.php file, simply add the configuration part in the app/config/config.yml file:

            token: s3cur3 # token used to clear the related cache
            php_cache_enabled: true # Optional (default: false), clear APC or PHP OPcache
            types: [translations] # Optional, you can restrict allowed cache types
                - { domain: kooqit.front1.local, ip:, port: 80}
                - { domain: kooqit.front2.local, ip:, port: 80}

As you can see, you have to define a token parameter that will secure your cache invalidation to avoid anybody clearing your cache.

A configuration parameter named php_cache_enabled will allow you to clear your APC or PHP OPcache code cache after having invalidate your Symfony cache.

The parameter named types allow you to restrict cache that can be cleared by defining the app/cache/environnement subdirectories the application is allowed to clear.

Then, the last step (and the biggest one) is to define your servers list with the domain name used by your application. SonataCacheBundle will establish a socket connection and make a HTTP call (with the given token) on your application.


Well, everything is done! You now just have to call the flush method in your controller or in your custom service. To do that, you can use/inject the service named sonata.cache.symfony.

So, to invalidate all Symfony cache:


Or, to invalidate only a part of the Symfony cache:


On writing a single line and a little part of configuration, you can invalidate your Symfony cache on multiple servers. Easy, no?.