PHP and Yii FRAMEWORK: use browser locale to set application locale

Using PHP 5.2.10 and Yii Framework 1.1.4 (http://www.yiiframework.com)

I wanted my web application to use messages in a language depending on the locale used by the web browser. According to the HTTP specification, browsers can send headers, in a request, to indicate preferred language, based on the user system.

At first I thought the framework would take care of this for me automatically, but that’s not the case (at least until this version). So we have to write some code to accomplish this.

First step is writing a CBehavior to set the application language during application startup. I created a file protected/components/StartupBehavior.php containing this:

<?php
class StartupBehavior extends CBehavior{
    public function attach($owner){
        $owner->attachEventHandler('onBeginRequest', array($this, 'beginRequest'));
    }

    public function beginRequest(CEvent $event){
        $language=Yii::app()->request->getPreferredLanguage();
        if ($language=='pt_br')
            $language='pt';
        Yii::app()->language=$language;
    }
}
?>

As you can see, the Yii framework already has a function to get the preferred language from the request headers, so we only have to set the language property in Yii::app().

Since I was building this application to work mainly to be accessed from Brazil, I had to change the language to ‘pt’ instead of ‘pt_br’ which is the value the browser would give me. I had to do this because Yii has no default message mappings to ‘pt_br’ (you can check the messages subdirectory in your framework installation to see if your language is already being mapped).

Now we need to load this CBehavior on startup. Just add the following to the array in protected/config/main.php

'behaviors'=>array(
    'onbeginRequest'=>array('class'=>'application.components.StartupBehavior'),
),
This entry was posted in programming and tagged , . Bookmark the permalink.

1 Response to PHP and Yii FRAMEWORK: use browser locale to set application locale

Leave a comment