![]() |
|
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.
Comments on this snippet
This snippet was very useful for my application and worked perfectly in version 0.6.3
However, after upgrading to 1.0.0-beta1, this snippet completely broke my application because symfony apparently changed the way filters were handled.
To get this working again, you have to add a method to the db filter class:
public function execute($filterChain){ $filterChain->execute(); return true; }
This will make your dynamic database selection work again!