Symfony2, Dynamic DB Connection/Early override of Doctrine Service

前端 未结 5 2044
别那么骄傲
别那么骄傲 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:41

    In symfony 4, you can pull it off with a wrapper class:

    # doctrine.yaml
    doctrine:
        dbal:
          connections:
            default:
              wrapper_class: App\Service\Database\DynamicConnection
    

    The class simply extends the original Connection:

    class DynamicConnection extends \Doctrine\DBAL\Connection
    {
    
        public function changeDatabase(string $dbName)
        {
            $params = $this->getParams();
    
            if ($this->isConnected())
                $this->close();
    
            if (isset($params['url'])) {
                $params['url'] = preg_replace(
                    sprintf("/(?<=\/)%s/", preg_quote($this->getDatabase())),
                    $dbName,
                    $params['url']
                );
            }
    
            if (isset($params['dbname']))
                $params['dbname'] = $dbName;
    
            parent::__construct(
                $params,
                $this->_driver,
                $this->_config,
                $this->_eventManager
            );
    
        }
    }
    

提交回复
热议问题