Sometimes you need to access the database information, such as dsn, database username or password from the databases.yml in your Symfony application. Since databases.yml is just a yml file, you can always find the file, parse the information in the file and read the information you want.
Needless to say this is a very arduous task, even with a yml parser. Furthermore, the fact that there are multiple environments in one single databases.yml can complicated the task of obtaining the correct set of variables.
An alternative way to do it is to use the underlying Symfony library. Suppose that you have the following databases.yml:
dev: db3: param: classname: DebugPDO test: db3: param: classname: DebugPDO dsn: 'mysql:dbname=mydbtest;host=localhost' all: db3: class: sfPropelDatabase param: classname: PropelPDO dsn: 'mysql:dbname=mydb;host=localhost' #where the db is located username: root password: password encoding: utf8 persistent: true pooling: true
Here's how you can obtain the dsn, username and password information from the above yml:
$appConfig= ProjectConfiguration::getApplicationConfiguration('frontend', 'test', true); $dbManager= new sfDatabaseManager($AppConfig); $db3=$dbManager->getDatabase('db3'); $username = $db3->getParameter('username'); //root $dsn= $db3->getParameter('dsn'); //mysql:dbname=mydbtest;host=localhost because it's test config $password= $db3->getParameter('password'); //password
Simple, isn't it?