How to user an application behavior for maintain runtime configuration

You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#2) »

In this tutorial will be explained a method for manage some configuration runtime. This excellent tutorial follows a similar approach, but requires to write a masterclass wich all controllers are supposed to extend, following this wiki you can achive the same editing only the configuration.

This is often needed for manage internationalization, themes and other confugration that depends from the user.

The most confortable way is to user an application behavior. In this example we save the language in the session, but can also be saved in database.

Create a file in compoments named ApplicationConfigBehavior and copy this code in it:

<?php
 
/**
 * ApplicationConfigBehavior is a behavior for the application.
 * It loads additional config paramenters that cannot be statically 
 * written in config/main
 */
class ApplicationConfigBehavior extends CBehavior
{
    /**
     * Declares events and the event handler methods
     * See yii documentation on behaviour
     */
    public function events()
    {
        return array_merge(parent::events(), array(
            'onBeginRequest'=>'beginRequest',
        ));
    }
 
    /**
     * Load configuration that cannot be put in config/main
     */
    public function beginRequest()
    {
       if (isset($_POST['lang']))
               $this->owner->user->setState('applicationLanguage', $_POST['lang']);
       if ($this->owner->user->getState('applicationLanguage'))
            $this->owner->language=$this->owner->user->getState('applicationLanguage');
        else 
            $this->owner->language='en';
    }
}

This file must be included in config/main.php:

'behaviors' => array('ApplicationConfigBehavior')

For update the language we can use a widget (to be included in layout/main), for example:

components/LangBox.php

<?php
class LangBox extends CWidget
{
    public function run()
    {
        $currentLang = Yii::app()->language;
        $this->render('langBox', array('currentLang' => $currentLang));
    }
}
?>

components/views/langBox.php

<?php echo CHtml::form(); ?>
    <div id="langdrop">
        <?php echo CHtml::dropDownList('_lang', $currentLang, array(
            'en_us' => 'English', 'is_is' => 'Icelandic'), array('submit' => '')); ?>
    </div>
<?php echo CHtml::endForm(); ?>
26 0
25 followers
Viewed: 43 162 times
Version: Unknown (update)
Category: How-tos
Written by: zaccaria
Last updated by: Pablovp
Created on: Jun 17, 2011
Last updated: 12 years ago
Update Article

Revisions

View all history

Related Articles