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: client1.simpledentalapp.com and one thing about is it they each need a separate database for security.
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):
$client_config = array( 'connectionString' => 'mysql:host=localhost;dbname=client1', 'emulatePrepare' => true, 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'tablePrefix'=>'', );
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.
Total 3 comments
Create virtual hosts on your dev box. You need to modify your hosts file.
modify httpd.conf
add entries in httpd-vhosts.conf
Read all about it!
There are probably some steps that I have forgotten. doodle
Yep, that should do it. Here's how my vhost entry looks:
Hi Thanks for this great idea how can this be set up localy when the SERVER_NAME is 127.0.0.1:8888 should it be with a httpd.conf change ?
Leave a comment
Please login to leave your comment.