Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change database connection Yii

I'm working on a project where multiple websites will be run from one Yii installation. Each website will have his own database though, so the database connection must be dynamically.

What i did, i created a BeginRequestBehavior which will be launched 'onBeginRequest'. Here i will check which url has been called and determine the matching database (not in my code yet) and create (or overwrite) the 'db' component.

<?php
class BeginRequestBehavior extends CBehavior
{

    /**
     * Attaches the behavior object to the component.
     * @param CComponent the component that this behavior is to be attached to
     * @return void
     */

    public function attach($owner)
    {

        $owner->attachEventHandler('onBeginRequest', array($this, 'switchDatabase'));

    }

    /**
     * Change database based on current url, each website has his own database.
     * Config component 'db' is overwritten with this value
     * @param $event event that is called
     * @return void
     */

    public function switchDatabase($event)
    {
        // Here some logic to check which url has been called..

        $db = Yii::createComponent(array(
            'class' => 'CDbConnection',
            'connectionString' => 'mysql:host=localhost;dbname=test',
            'emulatePrepare' => true,
            'username' => 'secret',
            'password' => 'verysecret',
            'charset' => 'utf8',
            'enableProfiling' => true,
            'enableParamLogging' => true
        ));

        Yii::app()->setComponent('db', $db);

    }
}

It's working fine, but is this the correct approach? In other approaches i see people creating their own 'MyActiveRecord' (extending CActiveRecord) for their models and putting the db component in a property. Why do they do it? I'm afraid the database connection will be made too many times than necessary this way.

like image 834
davey Avatar asked Feb 14 '26 05:02

davey


1 Answers

I use a model function for define her DB connection:

public static $conection; // Model attribute

public function getDbConnection(){

    if(self::$conection!==null)
        return self::$conection;

    else{
        self::$conection = Yii::app()->db2; // main.php - DB config name

        if(self::$conection instanceof CDbConnection){
            self::$conection->setActive(true);
            return self::$conection;
        }
        else
            throw new CDbException(Yii::t('yii',"Active Record requires a '$conection' CDbConnection application component."));
    }
}

main.php :

 'db'=>array( 
    'connectionString' => 'mysql:host=192.168.1.*;dbname=database1',
    'emulatePrepare' => true,
    'username' => 'root',
    'password' => 'password',
    'charset' => 'utf8',
    'enableProfiling'=>true,
    'enableParamLogging' => true,
),
'db2'=>array(
    'class'=>'CDbConnection',
    'connectionString' => 'mysql:host=192.168.1.*;dbname=database2',
    'emulatePrepare' => true,
    'username' => 'root',
    'password' => 'password',
    'charset' => 'utf8',
),
like image 120
Daniel Vaquero Avatar answered Feb 15 '26 19:02

Daniel Vaquero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!