phpauthenticationsymfonydoctrine-ormdbal

Symfony2: How to change Entity Manager just before doing login_check


I've two dbal connections. One static, defined in config.yml, and one defined dynamically. When I need it in a controller I set the connection parameters, such as host, database name, password, etc...

I need to set the dynamic connection just before doing the login check action (or in this action). This is because my "User" entity is on different databases according to the URL. So I can't put the dynamic connection definition in config.yml file.

I use that method to set the entity manager I need:

public function switchConnection($connectionParam=array()) 
{ 
    $conn = array_merge(
            array('host'=>'127.0.0.1', 'port'=>'3306', 'dbName'=>'myDatabaseName', 'user'=>'myUser', 'pass'=>'myPass',  'driver'=>'pdo_mysql', 'connection'=>'default', 'em'=>'default')
        , $connectionParam);

    $dbalConnectionTo=sprintf('doctrine.dbal.%s_connection', $conn['connection']); 
    $connection = $this->container->get($dbalConnectionTo); 
    $connection->close(); 
    $refConn = new \ReflectionObject($connection); 
    $refParams = $refConn->getProperty('_params'); 
    $refParams->setAccessible('public');

    $params = $refParams->getValue($connection); 
    $params['dbname'] = $conn['dbName']; 
    $params['user'] = $conn['user']; 
    $params['host'] = $conn['host']; 
    $params['port'] = $conn['port'];
    $params['password'] = $conn['pass']; 
    $params['driver'] = $conn['driver']; 
    $params['charset']='UTF8';

    $refParams->setAccessible('private');
    $refParams->setValue($connection,$params); 
    $this->container->get('doctrine')->resetEntityManager($conn['em']); 
    return; 
}

Could I change the "login_check" action code to set the Entity Manager my way?


Solution

  • In general it's bad practice to change the default database connection under a certain condition. Also the user needs to be loaded on any (logged in) request, not just in the login request.

    But there is of course a symfony way to achieve to load the user froma different database.

    You would need to implement your own UserProvider that loads the user from a different database connection. Here is an example of a userprovider.