title: Dynamically setting Doctrine EntityManager connection before each request in Symfony2
body: <p>I am working on a Symfony2 site that will host many sites, and each site will have its own database. I have implemented a service uses reflection to change connection parameters (username, password, dbname) on the 'client' entity manager. I'm not sure how to trigger this service before FOSUserBundle invokes its authentication services. I tried to create a Symfony2 Request event listener, but that doesn't seem to work:</p>
  
  <pre><code>class RequestListener {
      private $clientSiteContext;
  
      function __construct($clientSiteContext) {
          $this-&gt;clientSiteContext = $clientSiteContext;
      }
  
      public function onKernelRequest(GetResponseEvent $event) {
          if ($event-&gt;getRequestType() == HttpKernel::MASTER_REQUEST) {
              $this-&gt;clientSiteContext-&gt;resetClientEntityManager();
          }
      }
  }
  </code></pre>
  
  <p>resetClientEntityManager() implementation</p>
  
  <pre><code>public function resetClientEntityManager() {
      /** @var $doctrine \Doctrine\Bundle\DoctrineBundle\Registry */
      $doctrine = $this-&gt;container-&gt;get('doctrine');
  
      $dbConfig = $this-&gt;getConnectionParams();
      $dbalServiceName = sprintf('doctrine.dbal.%s_connection', 'client');
      $clientEmName = 'client';
  
      $connection = $this-&gt;container-&gt;get($dbalServiceName);
      $connection-&gt;close();
  
      $refConn = new \ReflectionObject($connection);
      $refParams = $refConn-&gt;getProperty('_params');
      $refParams-&gt;setAccessible('public');
  
      $params = $refParams-&gt;getValue($connection);
      $params['dbname'] = $dbConfig['dbname'];
      $params['user'] = $dbConfig['user'];
      $params['host'] = $dbConfig['host'];
      $params['password'] = $dbConfig['password'];
      $params['driver'] = $dbConfig['driver'];
      $params['charset'] = 'UTF8';
  
      $refParams-&gt;setAccessible('private');
      $refParams-&gt;setValue($connection, $params);
  
      $doctrine-&gt;resetEntityManager($clientEmName);
  }
  </code></pre>
  
  <p>Can someone advise how I can get this Listener to get call once for every page request, and for it to affect the Entity Manager that FOSUserBundle uses?</p>