Multiple Databases and Multiple Domains

You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#2)next (#4) »

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
		{
		
self::$db=new CDbConnection(Yii::app()->db2->connectionString,Yii::app()->db2->username,Yii::app()->db2->password);

if (isset(Yii::app()->db2->charset))
	self::$db->charset = Yii::app()->db2->charset;
if (isset(Yii::app()->db2->emulatePrepare))
	self::$db->emulatePrepare = Yii::app()->db2->emulatePrepare;
		
		
		// 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
15 followers
Viewed: 56 665 times
Version: Unknown (update)
Category: Tutorials
Tags: database
Written by: got 2 doodle
Last updated by: Maurizio Domba Cerin
Created on: Jul 30, 2010
Last updated: 14 years ago
Update Article

Revisions

View all history

Related Articles