mauriblint
mauriblint

Reputation: 1707

CakePHP3 switch database connection based on enviroment

I want to switch my default datasource based on the enviroment, or app domain.

'Datasources' => [
  'default' => [
      'className' => 'Cake\Database\Connection',
      'driver' => 'Cake\Database\Driver\Mysql',
      'persistent' => false,
      'host' => 'localhost'
  ],

  'local' => [
      'className' => 'Cake\Database\Connection',
      'driver' => 'Cake\Database\Driver\Mysql',
      'persistent' => false,
      'host' => 'localhost'
  ], 

  'stage' => [
      'className' => 'Cake\Database\Connection',
      'driver' => 'Cake\Database\Driver\Mysql',
      'persistent' => false,
      'host' => 'localhost'
  ] 
],    

Has CakePHP3 some logic to handle this kaind of thing? I cannot found anything useful in te documentation.

Thanks, Mauri.

Upvotes: 0

Views: 640

Answers (1)

GozaN
GozaN

Reputation: 11

When all the table on each db is same

You can use ConnectionManager::alias():

From Controller :

use Cake\Datasource\ConnectionManager;

if($somecase == "local") {
   ConnectionManager::alias('local', 'default');
else if($somecase == "stage") {
   ConnectionManager::alias('stage', 'default');
}
else {
  //cake will use default
}

more reference : http://api.cakephp.org/3.0/class-Cake.Datasource.ConnectionManager.html#_alias

Upvotes: 1

Related Questions