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

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Completely updated my answer, trying a different approach. Hope it helps.
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 what host? The database host? You can change the logic inside __construct() do do whatever you need.
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.