Reputation:
I was actually trying to implement SaaS architecture in Codeigniter with single Code-base and multiple databases...
To be clear, consider the following example : I've 3 clients namely client_1, client_2, client_3. I also have their respective databases - client_1_db, client_2_db, client_3_db.
So, my question is : there will be three urls with subdomains like - www.client_1.localhost.com, www.client_2.localhost.com and www.client_3.localhost.com. when any user requests for these urls, I have to select their respective databases for further process.
My project is being built with codeigniter and its HMVC..
thanks in advance..
Upvotes: 1
Views: 3991
Reputation: 81
In my experience, you should take care of three things.
First, a wildcard subdomain, to access your app from any subdomain (depends of your hosting/server settings).
Then, you should add your different DBs in config/database.php -> https://stackoverflow.com/a/8269596/953937
Then, you should read the $_SERVER['HTTP_HOST'] data to get subdomain, with subdomain you can load the respective DB... Should be something like this in core/MY_Controller.php
public function __construct() {
parent::__construct();
// get subdomain
$subdomain = explode('.', $_SERVER['HTTP_HOST'], 2);
$subdomain = $subdomain[0];
// check in main DB if client exists...
$this->db->from('table_of_clients')->where('slug', $subdomain);
$query = $this->db->get();
if($query->num_rows() < 1) {
header("Location: http://error.yourdomain.com");
} else {
// load client DB
$this->load->database($subdomain.'_db', TRUE);
}
}
Not tested, hope it works.
Regards!
Upvotes: 3