As the title would suggest this entry could be about the really nice translation mechanism provided by the symfony2 PHP framework (See ), but….. it isn’t….

Well, technically it’s not quite about the translation mechanism itself, it’s about the ease you can use a cookie to switch locales ( and languages as far as translation goes ).

In Symfony there is a translator component, which you can use to create translated pages on-the-fly, the only thing you need to do is to create language yaml files in the Bundle/Resources/translation folder which go by the following pattern <-domain->.<language>.yml.

Say we want to create texts for the ‘messages’ domain, and we would like to support both english and dutch. We therefore need to create 2 files, called messages.en.yml and In both files we create exactly the same keys, with the values being the text in the target language.

The nice thing about symfony 2 is that the translator component automatically chooses the appropriate resource file to use for the translation. This is done according to the active locale ( or the default & fallback settings in the symfony config file ). What I discovered today is that it’s possible to dynamically override the locale using a cookie and an Event listener..

If you create an event-listener for the KernelRequest event ( using an onKernelRequest handler function ) if which you extract the targetlocale from a cookie, and insert it into the request object (using setLocale(…) ) you can change the locale on the fly.  You still need to add the custom eventlistener to the processing chain, which you can do in the services.yml file.

At this moment I’m unable to post an example, but I will post an example soon, so please come back later… 🙂