Initialize Language

which is the best place to initialize the Yii::app()->language?

I don’t want to initialize in config/main.php because I am going to set that programmatically.

I thought to do that in components/controller.php but I am using a few modules which are not inherit the components/Controller class.

CController::init()

Check out the wiki: setting language in application.

So, I have to add language functionallity on "My Controller" to inherit all Controllers from this class. So if I have many "My Controllers" it could inherit the main "My Controller" (multi-level inheritance) right?

Yes.

And if you override init() method you need to call parent::init():


public function init() {

	parent::init();

	

	// your code here

}

there is by default "Controller" class in protected/components of which all other generated controllers are descendants. You can just put your init() code there.

Ha-ha, redguy… good old Cow & Chicken. :lol:

Yes I know that. But I have 2-3 different Controllers in components folder. Now I make it to inherit the base components/Controller. I run initialize it into __construct(). Thanks

yep :)

A bit late but another solution that is independent from the controller is to set the language in a handler for the ‘onBeginReuest’ application event. Here is the code for a behavior that does exactly that:




class SetLanguageBehavior extends CBehavior

{

    /**

     * @inheritDoc

     */

    public function events()

    {

        return array(

            'onBeginRequest' => 'beginRequestHandler',

        );

    }


    /**

     * Sets the language based on application configuration and browser settings.

     */

    public function beginRequestHandler($event)

    {

        $app = $this->getOwner();

        $lang = $app->getRequest()->getPreferredLanguage();


        // ADD YOUR OWN LOGIC HERE, E.G. SETTING THE LANGUAGE FROM THE DB

        

        if ($lang == $app->sourceLanguage)

            $lang = null;


        $app->setLanguage($lang);

    }

}



Then just add the behavior to the application in the main config:




...

    'behaviors' => array(

        'setLanguageBehavior' => array(

            'class' => 'SetLanguageBehavior',

        ),

    ),

...