Sub-domains with different databases in Yii!

You are viewing revision #2 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.

next (#3) »

Sub-domains with different databases in Yii!

  1. The set up
  2. The code

So my goal today is to explain how you can have the same core code powering multiple portals (sub-domains) without all the extra config fluff.

I used another example posted here a while back where the person was modifying the index.php and adding in a switch case for different domains and loading separate config files. This was actually too much for me, because all my portals are the exact same (as far as routes, modules, extensions, etc) and if I ever wanted to add another route it wouldn't be feasible opening up all the config files to do so. So the only thing that differs between my clients portals is in fact the database connection.

So let's get started:

I have a project where I give each client access to a their "portal" via say: client1.simpledentalapp.com and one thing about is it they each need a separate database for security.

The set up

Create a folder within your protected directory called clients (or whatever you want to call it).

Create a new file for each subdomain with different database credentials.

Each file should look like this (example: client1.php):

<?php
$client_config = array(
			'connectionString' => 'mysql:host=localhost;dbname=client1',
			'emulatePrepare' => true,
			'username' => 'root',
			'password' => '',
			'charset' => 'utf8',
			'tablePrefix'=>'',
);

The code

So inside of config/main.php I added the following code and changed the return array area to $config_array = array (...);

// remember, above this we have the entire config set to $config_array = array(...)
$exp = explode(".",$_SERVER['SERVER_NAME']);
$client_portal = trim(strtolower($exp[0]));
$root = dirname(__FILE__);
//remove trailing config dir, messy but hey...
$root = str_replace("/config", "", $root);

if(!file_exists($root.'/clients/'.$client_portal.'.php')) {
	die("Sorry, this client portal <strong>".$client_portal."</strong> is not set up or is invalid.");
}

// include db
include_once($root.'/clients/'.$client_portal.'.php');

// overwrite the db connection info from our included $client_config;
$config_array['components']['db'] = $client_config;

return $config_array;

And that's it. Pretty simple and a lot less headache when trying to manage just a simple database connection and nothing more.

Hope this helps someone. By the way, the example is using MySQL but Postgres and SQLite, etc will all work with this, the connection array just looks a little different.

2 0
12 followers
Viewed: 26 306 times
Version: Unknown (update)
Category: How-tos
Written by: jwerd
Last updated by: jwerd
Created on: Jun 2, 2011
Last updated: 13 years ago
Update Article

Revisions

View all history

Related Articles