On one of our projects that we use multiple connections that are defined at run time we recently were generating reports that required us to change a specific connection multiple times in a single run. We noticed that even though we would define a new connection, it would not throw any errors but just continue to use the originally defined connection. Here is how we were doing the connections:

<?php
$databaseManager = sfContext::getInstance()->getDatabaseManager();
$manager=Doctrine_Manager::getInstance();
$newConn = new sfDoctrineDatabase(array('dsn'=>'XXX','name'=> 'ExampleName'));
$newConn->connect();
$databaseManager->setDatabase('ExampleName',$newConn);

If you called the code above once, it would connect properly to the given DSN. However if you then called it a second time with a new DSN, it would not error and would simply just remain connected to the first DSN. After hunting around a bit it was the problem that Doctrine wasn’t assigning the new connection as the old connection was still open. To get around this we updated the code to the following:

<?php

$databaseManager = sfContext::getInstance()->getDatabaseManager();
$manager=Doctrine_Manager::getInstance();

// If the Doctrine Manager has the connection already close it so the new connection can be established
if($manager->contains('ExampleName'))
        $manager->closeConnection($manager->getConnection('ExampleName'));
$newConn = new sfDoctrineDatabase(array('dsn'=>'XXX','name'=> 'ExampleName'));
$newConn->connect();
$databaseManager->setDatabase('ExampleName',$newConn);

You need to first check to see if the Doctrine Manager has the connection, as if you try to get a connection that doesn’t exist, it will throw an exception.

Hope this saves you some time!