Mar. 8 2011
0

Creating database connections on-the-fly in Symfony

Symfony doesn’t have a documented way of created dynamic database connections. If I had to take a guess, it’s because database connections in Symfony don’t interact directly with the abstraction layer–the part that actually talks to the database–but instead interacts with the ORM layer–the part that turns results from the database into the objects you’re familiar with–which requires a model to function correctly. With that said, if you have another database that works off the same model as another connection (like master-slave server setups), then this could be for you.

To create a new database connection, you’ll need to create a new instance of an appropriate sfDatabase class. For instance, if you use Doctrine (as I do), you would use the sfDoctrineDatabase. Other class options are: sfPropelDatabase, sfMySQLDatabase, and sfPostgreSQLDatabase.

new sfDoctrineDatabase(array(
  'name'          => 'newConnection', 
  'dsn'            => 'mysql:host=127.0.0.1;dbname=newDatabase', 
  'username'    => 'user1',
  'password'    => 's3c!437',
));

Notice that you don’t have to set the variable to anything for the connection to be created, it’s automatically added to the internal database manager. The name param will be used to distinguish it among the other connections.

You can also override a current database connection by using the same name, but be care: the model binded to connection must be the same or you will run into 500 errors.

If you use the Doctrine ORM/DBAL (which is, by default, what Symfony uses), you can bind a model to a connection so it will be used with a particular connection instead of by all. To do that, simply put this at the top of your model base class:

// TableBase.class.php
Doctrine_Manager::getInstance()->bindComponent('Table', 'newConnection');

Sadly, I’m not versed at all with Propel and I don’t know how to bind a model to a connection, or even if it is possible to do so. If anyone does know, please let me know in the comments.

Leave a Reply

Previous post:

Next post:

Last.fm interface from fmTuner (modified by me).

Twitter interface from HL Twitter.

Dedicated to my mom, Sharon. May she rest peacefully.
Love you always. (March 23, 1965 - November 12, 2011)

Unsupported Browser!

My site is designed for and currently displays best with modern browsers (and it looks like you don't have one!).

Everything should still function properly, but you won't be able to see all the fancy effects, text, or the way I intended my design to look.

Consider trying the latest version of either Firefox or Chrome... I think you'll like it!

Logan Bibby

P.S.: You can continue viewing my site by clicking the "close" link and you'll never see this again. :)