Yii 1.1: Multiple Databases and Multiple Domains

17 followers

How to connect to two databases simutaneously

Add these lines in /config/main.php

'components'=>array(
.........
        'db'=>array(
            'connectionString' => 'mysql:host=localhost;dbname=database1',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => 'itsasecret',
            'charset' => 'utf8',
        ),
        'db2'=>array(
            'class' => 'CDbConnection',
            'connectionString' => 'mysql:host=localhost;dbname=database2',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => 'itsasecret',
            'charset' => 'utf8',
        ),
....
),

Create a new file in protected/components, this example is called AltActiveRecord.php


abstract class AltActiveRecord extends CActiveRecord
{
    const BELONGS_TO='CBelongsToRelation';
    const HAS_ONE='CHasOneRelation';
    const HAS_MANY='CHasManyRelation';
    const MANY_MANY='CManyManyRelation';
    const STAT='CStatRelation';
 
    /**
     * @var CDbConnection the default database connection for all active record classes.
     * By default, this is the 'db' application component.
     * @see getDbConnection
     */
    public static $db;
 
    private static $_models=array();            // class name => model
 
    private $_md;                               // meta data
    private $_new=false;                        // whether this instance is new or not
    private $_attributes=array();               // attribute name => attribute value
    private $_related=array();                  // attribute name => related objects
    private $_c;                                // query criteria (used by finder only)
    private $_pk;                               // old primary key value
 
    /**
     * Returns the database connection used by active record.
     * By default, the "db" application component is used as the database connection.
     * You may override this method if you want to use a different database connection.
     * @return CDbConnection the database connection used by active record.
     */
    public function getDbConnection()
    {
        if(self::$db!==null)
            return self::$db;
        else
        {
 
            // Create CDbConnection and set properties
            self::$db = new CDbConnection();
            foreach(Yii::app()->db2 as $key => $value)
                self::$db->$key = $value;
 
 
        // Uncomment the following lines to prove that you have two database connections
        /*
            CVarDumper::dump(Yii::app()->db);
            echo '<br />';
            CVarDumper::dump(Yii::app()->db2);
            die;
        */
            if(self::$db instanceof CDbConnection)
            {
                self::$db->setActive(true);
                return self::$db;
            }
            else
                throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
        }
    }
}

For each model using the second database,extend the above file example;


/**
 * This is the model class for table "pagedata".
 */
class Pagedata extends AltActiveRecord
{
..
// model stuff here
..
}

Your application should now have access to two databases simultaneously.


Multiple Domains with one entry script

Now for multiple sites (multiple domains) using one installation of Yii and one entry script, example parked domains.


Modify index.php as shown below.

// change the following paths if necessary
$hostname = $_SERVER['SERVER_NAME'];
$yii=dirname(__FILE__).'/../../framework/yii.php';
 
switch ( strtolower($hostname))
{
case 'example1.com';
case 'www.example1.com';
    $config=dirname(__FILE__).'/protected/config/main.php';
    // database 1
break;
case 'example2.com';
case 'www.example2.com';
    $config=dirname(__FILE__).'/protected/config/main2.php';
    // database 2
break;
 
case 'example3.com';
case 'www.example3.com';
    $config=dirname(__FILE__).'/protected/config/useAnyName.php';
    // database 3 
break;
 
default:
$config=dirname(__FILE__).'/protected/config/main.php';
}
// remove the following lines when in production mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);
 
require_once($yii);
Yii::createWebApplication($config)->run();

In each config file you can specify numerous parameters that are site specific.


// application-level parameters that can be accessed
    // using Yii::app()->params['paramName']
    'params'=>array(
        // this is used in contact page
        'adminEmail'=>'admin@example1.com',
        'googleCode'=>'UA-2****8-11',
        'juitheme'=>'dark-hive',
        'cssfile'=>'cwdi'
    ),

For example styling could be set for each domain name like this (in layout.php)

<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/<?php echo Yii::app()->params->cssfile; ?>.css" />

I hope this helps someone

doodle

Total 2 comments

#4432 report it
phreak at 2011/07/08 09:53am
Transaction not working

By creating another instance of CDBconnection it will not use the active transcation of the db component. You shoul just return Yii::app()->db2 instead of making a copy of the params.

#3522 report it
WallTearer at 2011/04/17 02:28pm
Works

Thanks a lot, man, for the hint about multiple databases. Worked for me after the first run, very nice, thanks!

Leave a comment

Please to leave your comment.

Write new article