![]() |
|
Snippets |
|
In app/lib/ create a file named myDBConnectionFilter.class.php and add:
class myDBConnectionFilter { public function initialize($filterChain) { $db = sfContext::getInstance()->getDatabaseManager()->getDatabase('myschema'); $db->setConnectionParameter('username', 'myusername'); $db->setConnectionParameter('password', 'mypassword'); $db->setConnectionParameter('hostspec', 'localhost'); $db->setConnectionParameter('database', 'mydatabase'); // The below line is optional - Symfony will connect anyway if no connection is present $db->connect(); } }
Then declare this filter to run on every page load by adding this to app/config/filters.yml:
myDBConnectionFilter:
class: myDBConnectionFilter
Finally, Symfony will fail at the call above
sfContext::getInstance()->getDatabaseManager()->getDatabase('myschema');
because it does not know what type of database driver 'myschema' requires (MySQL/SQLite/etc.). You must add the following to app/config/databases.yml:
all:
propel:
class: sfPropelDatabase
param:
phptype: mysql
You can now dynamically select databases from the above class.
To modify the settings of a connection named 'propel':
$con = sfContext::getInstance()->getDatabaseConnection('propel'); $con->setConnectionParameter('username', 'foo'); $con->setConnectionParameter('password', 'bar');
This works for all the settings that can be defined in the databases.yml (more info in the sfPropelDatabase class source).
You must execute this code before the first query to the database. If you do that after a first query, it fails. This means that the best way to implement it is in a filter.