La guida si ispira al tutorial originale inglese denominato
How to use an application behavior to maintain runtime configuration
Da quello che ho capito finora il behavior è uno strumento molto potente che ci offre yii ed è bene capirlo a fondo.
Per farlo proveremo a gestire configurazioni lato utente molto diffuse nelle web applicaton, come l'internalizzazione, la lingua e la data che possono cambiare a seconda del paese.
In questo esempio salviamo la lingua selezionata dall'utente in sessione.
1) Creare un file in /protected/components denominato ApplicationConfigBehavior.php contenente questo codice:
<?php
/**
* ApplicationConfigBehavior is a behavior for the application.
* It loads additional config parameters that cannot be statically
* written in config/main
*/
class ApplicationConfigBehavior extends CBehavior
{
/**
* Declares events and the event handler methods
* See yii documentation on behavior
*/
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';
}
}
2) Questo file dev'essere incluso in /protected/config/main.php. Quindi nell'array bisogna aggiungere:
'behaviors' => array('ApplicationConfigBehavior')3) Per aggiornare la lingua possiamo utilizzare un widget (da inserire nel layout / main), ad esempio:
/protected/components/LangBox.php
<?php
class LangBox extends CWidget
{
public function run()
{
$currentLang = Yii::app()->language;
$this->render('langBox', array('currentLang' => $currentLang));
}
}
?>/protected/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(); ?>

Help




Non preoccuparti, è dentro il monitor!










