Symfony2, Dynamic DB Connection/Early override of Doctrine Service

前端 未结 5 2046
别那么骄傲
别那么骄傲 2020-11-29 04:24

I have a Core config Database, each row is an \'App\' with some basic config etc.
Once you have chosen your app, I want to connect to a database using a property of that

5条回答
  •  心在旅途
    2020-11-29 04:42

    Here is the new and improved non-reflection version

    #services.yml
    acme_app.dynamic_connection:
        class: %acme.dynamic_doctrine_connection.class%
        calls:
            - [setDoctrineConnection, [@doctrine.dbal.default_connection]]
    
    
    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;
        }
    }
    

提交回复
热议问题