1

I have an application where each subscriber gets their own 'app' folder within their own url eg.

www.domain.com/1234 subscriber1
www.domain.com/2345 subscriber2

now the db connection is configured in a class in config/database.php. I want to be able to change the database used based on the url (eg. /1234 = db_1234).

How would I achieve this?

Thanks

BTW I am using CakePHP 2.0

Oldskool
  • 34,211
  • 7
  • 53
  • 66
khany
  • 1,167
  • 15
  • 33
  • Maybe http://stackoverflow.com/questions/5512327/cakephp-switch-database-using-same-datasource-on-the-fly will help you – gustavotkg Nov 29 '11 at 14:58

2 Answers2

2

My previous solution was a load of rubbish. So I thought about attacking the problem from a different angle. My DATABASE_CONFIG class (/app/Config/database.php) now looks like this:

class DATABASE_CONFIG {

  public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => '127.0.0.1',
    'login' => 'xxxx',
    'password' => 'xxxx',
    'database' => 'xxxx',
    'prefix' => '',
    'encoding' => 'utf8',
  );

  public $site_one = array(
    'datasource' => 'Database/Mysql',
    'host' => '127.0.0.1',
    // ...  
  );

  public $site_two = array(
    'datasource' => 'Database/Mysql',
    'host' => '127.0.0.1',
    // ...
  );

  public function __construct()
  {
    if (strpos(env('HTTP_HOST'), 'site_one') !== false) {      

      // use site_one database config
      $this->default = $this->site_one;

    // elseif site_two
    } elseif (strpos(env('HTTP_HOST'), 'site_two') !== false) {

      // use site_two database config
      $this->default = $this->site_two;
    }
  }

}

When Cake loads, the construct is now called automatically, and this sets the 'default' database connection dependent on the host.

Moz Morris
  • 6,681
  • 2
  • 20
  • 18
  • Completely updated my answer, trying a different approach. Hope it helps. – Moz Morris Nov 29 '11 at 15:45
  • its sort of what I'm after but you are still hardcoding the connection vars in the config file. Can the host be set dynamically as the page is loaded based on the folder name? – khany Nov 29 '11 at 16:38
  • 1
    @khany what host? The database host? You can change the logic inside __construct() do do whatever you need. – Moz Morris Nov 29 '11 at 16:52
0

Ah I got it now,

I thought DATABASE_CONFIG was called statically so didn't think to use the construct.

www.domain.com/12345678

function __construct() {
    // get folder
    if(substr(php_sapi_name(), 0, 3) == "cli") {
        $j = explode("/", $_SERVER['PWD']);
        $this->default['database'] = "sa_".$j[count($j)-1];
    } else {
        $j = explode("/", $_SERVER['REQUEST_URI']);
        $this->default['database'] = "sa_".$j[1];
    }
}

but commandline bake must be done in folder eg. 12345678/

khany
  • 1,167
  • 15
  • 33