Difference between #2 and #3 of Sub-domains with different databases in Yii!

unchanged
Title
Sub-domains with different databases in Yii!
unchanged
Category
How-tos
unchanged
Tags
multiple database connection, database, connection, multisite, multi-site, subdomains, sub-domains
changed
Content
Sub-domains with different databases in Yii!
========
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: <a
href="http://client1.simpledentalapp.com"href="http://client1.simpledentalapp.com.com"
title="example">client1.simpledentalapp.com</a> 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]
<?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 (...);

~~~
[php]
// 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.