gpt4 book ai didi

php - Symfony:动态更改数据库

转载 作者:可可西里 更新时间:2023-10-31 22:08:52 24 4
gpt4 key购买 nike

假设我有 3 个数据库:

  • prefix_db1
  • prefix_db2
  • prefix_db3

我想从这样的 url 动态连接到它们 http://localhost/my-project/web/app_dev.php/db1/books 所以我知道要连接到哪个数据库来自 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 http://localhost/my-project/web 登录(当然每个数据库都有 user 表)时/app_dev.php/db1/login我得到这个异常:

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

如你所见,symfony 尝试使用 parameters.yml 中声明的 database_name 登录用户,这意味着 symfony 的 security_checker 具有在我的听众之前和覆盖 Doctrine 的 params 之前被解雇。

我的问题:
有没有办法在任何其他 http 请求监听器之前触发我的监听器?或者可能是一种替代解决方案,以确保对数据库的任何请求都必须使用正确的数据库名称。
很抱歉发了这么长的帖子。

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

The other optional tag attribute is called priority, which defaults to 0 and it controls the order in which listeners are executed (the highest the priority, the earlier a listener is executed). This is useful when you need to guarantee that one listener is executed before another. The priorities of the internal Symfony listeners usually range from -255 to 255 but your own listeners can use any positive or negative integer.

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

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

但问题依然存在,在 symfony 之前仍然无法触发我的监听器!

最佳答案

我找到了解决办法
这个想法是更改 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 requestes

触发监听器

关于php - Symfony:动态更改数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53151669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com