Dear life_free
I hope the following will serve the purpose.
1.Create a controller action and view to choose the database.
view-serverAllot
<?php
echo CHtml::beginForm();
echo CHtml::dropDownList('server','server1',array('server1'=>'adminServer','server2'=>'normalServer'));
echo CHtml::submitButton('submit');
echo CHtml::endForm();
?>
<div style="margin-top:10px;font-size:16px;">
<?php
if(Yii::app()->user->hasState('server')) {
if(Yii::app()->user->getState('server')=='adminServer')
echo "You are currently using admin server";
elseif(Yii::app()->user->getState('server')=='routineServer')
echo "You are currently using routine server";
}
?>
</div>
action
public function actionServerAdmin()
{
if(isset($_POST['server']))
{
if($_POST['server']=='server1')
Yii::app()->user->setState('server','adminServer');
elseif($_POST['server']=='server2')
Yii::app()->user->setState('server','routineServer');
}
$this->render('serverAllot');
}
By making it into persistant state, we can work across many requests and controllers.
2.Create an application behavior and attach it to main application.
applicationBehavior.php in components directory
<?php
class applicationBehavior extends CBehavior
{ private $_owner;
public function events() {
return array(
'onBeginRequest'=>'changeDb',
);
}
public function changeDb(){
$owner=$this->_owner=$this->getOwner();
if($owner->user->hasState('server') && $owner->user->getState('server')=='adminServer')
{
$owner->db->setActive(FALSE);
//admin-the new database.
$owner->setComponent('db',new CDbConnection("mysql:host=localhost;dbname=admin",'root','yourpassword'));
$owner->db->setActive(TRUE);
}
}
}
?>
Attach this behavior instance as a property to main configuration file. Leave the ‘db’ component intact.
main.php
return array(
......................................
.......................................
'behaviors'=>array(
'class'=>'application.components.applicationBehavior',
),
......................................
......................................
'components'=>array(
.........................................
........................................
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=routine',//rotine-default database
'emulatePrepare' => true,
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
),
.....................................................
....................................................
),
)
You can create new models by creating new tables in the database(admin) for exclusive use in admin pages.
If you want to share already created models, your new tables should exactly simulate the tables in routine data
base. Ofcoures you can easily import and export tables.
Regards.