1

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..

  • How on earth do we know if you want to eat this code or dance with the code or...?.. Also please provide what have you tried so far – BILAL MALIK Feb 19 '19 at 12:11
  • No, actually I need to convert my existing codeigniter project into SaaS architecture. Instead of having multiple code-base (which is same) why not to make it constant and use different databases dynamically based on urls (mentioned above). –  Feb 19 '19 at 12:16
  • there is no question here, merely statements of what you want without any research or effort. – Alex Feb 19 '19 at 13:58
  • oh come on, If I got the answer through research and effort then why would I ask the question here? There is NO much materials online related to this...!! –  Feb 20 '19 at 05:13

1 Answers1

2

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!