I want to set the database config from CakePhP 2.x with data from database
Example - database.config:
public $bd_test = array (
'datasource' => 'Database/Postgres',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => 'root',
'database' => 'bd_test',
'port' => '5432',
//'encoding' => 'UTF-8'
);
Should looks like:
$dataFromDb = $this->Model->find('all', array('fields' => array('host', 'login', 'password', 'database', 'port'), 'conditions' => array('database' => 'bd_test')));
public $bd_test = array (
'datasource' => 'Database/Postgres',
'persistent' => false,
'host' => $dataFromDb['host'],
'login' => $dataFromDb['login'],
'password' => $dataFromDb['password'],
'database' => $dataFromDb['database'],
'port' => '5432',
//'encoding' => 'UTF-8'
);
Something like that.. I guess that the Idea is clear, right? If need some more information, please tell me. Thanks.
You should be able to set config-datasets at runtime with Configure::write('nameofconfigfield,'value');
If this does'nt work, I'm sorry. I'm not familiar with CakePHP 2.x, I only used 3.x.
I answered like I understood your question. But I don't know what you want to achieve with changing the DB connection at runtime.
I found the solution:
public function beforeFilter(){
App::uses('ConnectionManager', 'Model');
$databases = $this->YourModel->find('all');
foreach($databases as $valor){
foreach($valor as $value){
$settings = array(
'datasource' => 'Database/Postgres',
'persistent' => false,
'host' => $value['host'],
'login' => $value['user'],
'password' => $value['password'],
'database' => $value['database'],
'port' => $value['port']
);
ConnectionManager::create($value['nome_banco'], $settings);
}
}
}
And Later I had to do setDataSource
or you can replace the default connection with : ConnectionManager::create('default', $settings); Right this:
ConnectionManager::getDataSource('default')->disconnect();
ConnectionManager::drop('default');
ConnectionManager::create('default', $settings);
But how I want to use both connections I didn't that. Thanks to M4R1KU that helped me.