Reputation:
My Question is : on CakePHP : How to use and connect alternative database config when it's failed to connect to DB?
Based on my question above, just give you the idea that on traditional php programming, we can do like this :
$db_configs=array(
0=>array('host'=>'localhost1','user'=>'root1','password'=>'password1'),
1=>array('host'=>'localhost2','user'=>'root2','password2'=>'password2')
);
foreach($db_configs as $db_config)
{
if(!mysql_connect($db_config['host'],$db_config['user'],$db_config['password'])
{
// DB Connection Failed, do nothing and try next db config...
}
else
{
echo 'DB Connection Success, Break';
break;
}
}
So the idea is, the script try to reconnect to database when it's failed and using alternative config variable.
How can we do like that on CakePHP ?
Thank you.
Upvotes: 1
Views: 598
Reputation: 25698
Define your two or more configs in APP/config/database.php. Then do the check in bootstrap.php
$Database = ConnectionManager::getInstance();
$Database->config = new DATABASE_CONFIG();
$dataSource = $Database->getDataSource('default');
if (!$dataSource->isConnected()) { ... } else { ... }
"default" is the default connection, just use $Database->getDataSource('yourSecondDataSource') to use another one in the case the first one fails.
Upvotes: 1