Symfony:动态更改数据库

时间:2018-11-05 09:34:04

标签: php symfony doctrine

假设我有3个数据库:

  • prefix_db1
  • prefix_db2
  • prefix_db3

我想像这样http://localhost/my-project/web/app_dev.php/db1/books从URL动态连接到它们,所以我知道从URL(在这种情况下为prefix_db1)连接到哪个数据库
基本上,这个想法是准备一个将随每个 http请求触发的监听器,从url获取数据库名称,然后覆盖doctrin的参数,如下所示:
services.yml 中:

dynamic_connection:
        class: AppBundle\service\DynamicDBConnector
        arguments:  ['@request_stack']
        calls:
            - [ setDoctrineConnection, ['@doctrine.dbal.default_connection'] ]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

我的听众:

<?php    
namespace AppBundle\service;

use Doctrine\DBAL\Connection;
use Symfony\Component\HttpFoundation\RequestStack;
use Exception;

class DynamicDBConnector
{
    /**
     * @var Connection
     */
    private $connection;

    /*
     * @var Request
     */
    private $request;


    public function __construct(RequestStack $requestStack)
    {
        $this->request = $requestStack->getCurrentRequest();

    }

    /**
     * Sets the DB Name prefix to use when selecting the database to connect to
     *
     * @param  Connection       $connection
     * @return DynamicDBConnector $this
     */
    public function setDoctrineConnection(Connection $connection)
    {
        $this->connection = $connection;
        return $this;
    }

    public function onKernelRequest()
    {
        if ($this->request->attributes->has('_company')) {

            $connection = $this->connection;
            $params     = $this->connection->getParams();

            $companyName = $this->request->get('_company');
            // I did the concatenation here because in paramaters.yml I just put the prefix (database_name: prefix_) so after the concatenation I get the whole database name "prefix_db1"
            $params['dbname'] = $params['dbname'] . $companyName;

            // 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;
    }
}

现在这很好用了,我已经用一个简单的书籍列表对其进行了测试,每次更改url时,我都会得到与每个数据库相关的列表:

http://localhost/my-project/web/app_dev.php/db1/books // I get books of database prefix_db1

http://localhost/my-project/web/app_dev.php/db2/books // I get books of database prefix_db2

现在让我们解决问题吧:)
现在的问题是,当我使用身份验证系统保护我的项目并尝试使用此URL user登录(当然每个数据库都有http://localhost/my-project/web/app_dev.php/db1/login表)时 我遇到这个异常:

An exception occured in driver: SQLSTATE[HY000] [1049] Base 'prefix_' unknown

您可以看到symfony尝试使用 parameters.yml 中声明的database_name登录用户,这意味着symfony的security_checker已在我的监听器和在覆盖教义的params之前。

我的问题
有没有办法在其他任何HTTP请求侦听器之前触发我的侦听器?或者可能是另一种解决方案,以确保对数据库的任何请求都必须使用正确的数据库名称。
抱歉,长篇文章。

编辑:
来自symfony的官方文档:
https://symfony.com/doc/2.3/cookbook/event_dispatcher/event_listener.html

  

另一个可选标签属性称为优先级,默认情况下   设为0,并控制侦听器的执行顺序(   优先级最高,则监听器执行得越早)。这是   当您需要确保在执行之前先执行一个侦听器时很有用   另一个。内部Symfony侦听器的优先级通常   范围从-255到255,但您自己的听众可以使用任何正数或   负整数。

我将侦听器的优先级设置为 10000

tags:
    - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 10000 }

但是问题仍然存在,仍然无法在symfony之前解雇我的听众!

3 个答案:

答案 0 :(得分:5)

我找到了解决方法
想法是更改symfony用于创建数据库连接的默认Connection类:

doctrine:
    dbal:
        connections:
            default:
                wrapper_class: AppBundle\Doctrine\DynamicConnection
                driver: pdo_mysql
                host: '%database_host%'
                port: '%database_port%'
                dbname: '%database_name%'
                user: '%database_user%'
                password: '%database_password%'
                charset: UTF8

之后,我们可以在构造函数中更改给定的参数:

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver;

class DynamicConnection extends Connection
{
    public function __construct(array $params, Driver $driver, $config, $eventManager)
    {
        $params['dbname'] = 'teqsdqsdqst';
        parent::__construct($params, $driver, $config, $eventManager);
    }
}

现在,我们只需要从url中获取参数并在$params['dbname']内进行设置即可。
这样,我们确保symfony将始终使用此类创建连接,并且不再需要使用 http请求

触发监听器

答案 1 :(得分:2)

很好的解决方案,但是如果您想从URL获取参数_company,则可以通过传入参数的EventManager对象在构造函数内部检索容器,并从中获取当前请求,实际上容器被注入ContainerAwareEventManager的子类EventManager

class DynamicDBConnector extends Connection
{
    public function __construct($params, $driver, $config, $eventManager)
    {
        if(!$this->isConnected()){
            // Create default config and event manager if none given (case in command line)
            if (!$config) {
                $config = new Configuration();
            }
            if (!$eventManager) {
                $eventManager = new EventManager();
            }

            $refEventManager = new \ReflectionObject($eventManager);
            $refContainer = $refEventManager->getProperty('container');
            $refContainer->setAccessible('public'); //We have to change it for a moment

            /*
             * @var \Symfony\Component\DependencyInjection\ContainerInterface $container
             */
            $conrainer = $refContainer->getValue($eventManager);

            /*
             * @var Symfony\Component\HttpFoundation\Request
             */
            $request = $conrainer->get('request_stack')->getCurrentRequest();

            if ($request != null && $request->attributes->has('_company')) {
                $params['dbname'] .= $request->attributes->get('_company');
            }

            $refContainer->setAccessible('private'); //We put in private again
            parent::__construct($params, $driver, $config, $eventManager);
        }
    }
}

答案 2 :(得分:0)

您应该像这样在config.yml中添加数据库名称:

 orm:
        auto_generate_proxy_classes: '%kernel.debug%'
#        naming_strategy: doctrine.orm.naming_strategy.underscore
#        auto_mapping: true
        default_entity_manager: default
        entity_managers:
            default:
                connection: default
                mappings:
                    DataMiningBundle: ~
                    AppBundle: ~
                    UserBundle: ~

            your_second_db:
                connection: your_second_db (decalared in parameters.yml)
                mappings:
                    yourBundle: ~

并从您的控制器调用它:

 $em = $doctrine->getConnection('your_second_db');