Dynamic Propel/Doctrine connection

Sometimes you may need to change access to database dynamically inside your project (may be very usefull for sharding approaches). Also wondering what if disable DB access at all from config/settings.yml:

use_database:           false

and create connection only where it’s needed. I’m sure this would speed up performance fantastically. Although almost every page wants to get something from DB 🙂

So it’s not complicated but also not well highlighted in manuals, quick way to create dynamically DB connection in Doctrine:

$db = sfContext::getInstance()->getDatabaseManager()->getDatabase('doctrine');
$db->getDoctrineConnection()->setOption('username', 'yourdbusername');
$db->getDoctrineConnection()->setOption('password', 'yourdbuserpassword');
$db->getDoctrineConnection()->setOption('dsn', "mysql:host=localhost;dbname=yourdbname");

I’ve also found in snippets this code for Propel (did not test if it would work with latest symfony though):

$dsn = Creole::parseDSN('mysql://localhost/symfony');
$c = Propel::getConfiguration();
$c['datasources'][$name]['connection'] = $dsn;
$c['datasources'][$name]['adapter']    = $dsn['phptype'];

So just a quick note for now
Chiao! 🙂