Multi-lingual routing in CakePHP

Monday 22nd June 2009

After trialing various web development frameworks we have settled on CakePHP at work. I have managed to convince the developers we should ditch our custom made MVC framework and we haven’t looked back since.

This week I started using Cake for a fairly ambitious project – a pan European multi-lingual website for Honda. The site isn’t particularly complex in nature but it is a project in which I can test and utilise lots of the in-built functionality in Cake. Essentially the site will be powered by XML and each country will have its own XML file containing country-specific content. The correct XML document will be pulled in based on a valid country/language code being supplied in the URL string. This is how I accomplished getting custom country-specific URLs working in Cake:

The URL structure I want is
http://www.mydomain.com/en_GB/pages/home
where en_GB is the language/country code.

Firstly I set a variable in the config.php file called language:
Configure::write('language', 'en_GB');
This sets the default language of the site to be English (Great Britain) so in the event of an invalid or unsupplied country code it would default back to to this.

I then modified the routes.php file:
Router::connect('/:language/:controller/:action/*', array(), array());
This uses the language variable I defined above.

Finally in my AppController class I check using the beforeFilter function that the supplied language is valid and then update the config if it is, i.e.: Configure::write(’language’, ‘fr_FR’); The visitor’s preference is then stored in a cookie.

For first time visitors the language is set using a country lookup on IP address service.

Tags: , ,

Contact

Twitter Linked In Facebook Flickr last.fm Gmail