Multiple Databases and Multiple Domains

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

13 2
16 followers
Viewed: 49 625 times
Version: 1.1
Category: Tutorials
Tags: database
Written by: got 2 doodle
Last updated by: Maurizio Domba Cerin
Created on: Jul 30, 2010
Last updated: 10 years ago
Update Article

Revisions

View all history

Related Articles