这是新的和改进的非反射版本
#services.ymlacme_app.dynamic_connection: class: %acme.dynamic_doctrine_connection.class% calls: - [setDoctrineConnection, [@doctrine.dbal.default_connection]]<?phpnamespace AcmeBundleAppBundle;use DoctrineDBALConnection;use SymfonyComponentHttpKernelExceptionServiceUnavailableHttpException;use Exception;class DynamicDoctrineConnection{ private $connection; public function setDoctrineConnection(Connection $connection) { $this->connection = $connection; return $this; } public function setUpAppConnection() { if ($this->request->attributes->has('appId')) { $connection = $this->connection; $params = $this->connection->getParams(); // we also check if the current connection needs to be closed based on various things // have left that part in for information here // $appId changed from that in the connection? // if ($connection->isConnected()) { // $connection->close(); // } // Set default DB connection using appId //$params['host'] = $someHost; $params['dbname'] = 'Acme_App'.$this->request->attributes->get('appId'); // Set up the parameters for the parent $connection->__construct( $params, $connection->getDriver(), $connection->getConfiguration(), $connection->getEventManager() ); try { $connection->connect(); } catch (Exception $e) { // log and handle exception } } return $this; }}


