As we know, CakePHP is prepare to deal with multilingual sites making use of i18n and l10n and its
We can set a language by default by using the configure statement:
But if we want to enable the user to change the language on their settings page, for example, we need something else.
Changing language in real time
Well, lets imagine we have a site and we have those lovely language flags at the header. We want to be able to click on our flag and be redirected to the same exact URL in which we were.
How can we accomplish it? Well, first of all, we will make the changes over the session as pointed in CakePHP documentation in order to change the language in real time.
That’s what we are going to do once the user click over the flag, so we will need to define where are we going to redirect the user in that case.
We could place an action in a particular controller or we could better place it in the
AppController as it will be called from any controller.
We will call it
changeLanguage and it will admit one parameter as the shortcurt of the language we want to change to.
This way, it will look like this:
And that’s it. We already have a site which allow to change the language in real time.
And what if we want to detect the user’s language and set the page on that language?
We could try to read the IP and determine which country the user comes from but, besides being a bit tedious, I don’t personally like the idea. What if I am in USA but I am mexican and I speak spanish? What if I am at holidays in Tokio with my laptop but I only know english?
I have always found much more reasonable, useful and simple, to detect the language of the user’s browser and act accordingly.
We can get the browser language with PHP using the $_SERVER variable:
That would return us a list of the favorite languages for our browser in order. Something like this:
If we get the first one, we will get the favorite language which is usually the one we want to get:
We will make use of this technique the first time the user enters in our page or anytime the language session is not defined. As you can guess, as we want to do it from any section of our site, we will place it in our
AppController. And as we want it to be executed at any time, we will do it on the
I would recommend creating a protected function and calling it from the
Join 2,000+ readers and learn something new every month!