gpt4 book ai didi

php - 在 Symfony 中使用 config.php 和 doctrine.yaml 使用动态数据库名称

转载 作者:行者123 更新时间:2023-12-05 03:00:02 27 4
gpt4 key购买 nike

我设置了一个 symfony 项目。我所有的数据库连接都在 app/.env 中。

这是我在 .env 文件中配置的方式:

DATABASE_URL=mysql://root@127.1.0.1:3306/abcdefg

现在我想使用像 config.php 这样的 .php 文件,我可以在其中存储数据库配置的值,应用程序也应该使用相同的文件而不是从 .env 文件中获取值。

这是根据应用程序 URL 连接不同的数据库。所以数据库名称取决于 URL。

为了使其动态化,我想使用 PHP 文件而不是 .env 文件。

最佳答案

(假设您使用的是 Symfony 版本 4 或更高版本 - 但稍作修改后也应该可以在早期版本中使用)

第 1 部分 - 从 php 加载容器参数

  1. 像这样创建文件“config/my_config.php”:
<?php

$container->setParameter('my_param', 'something1');

$elements = [];
$elements[] = 'yolo1';
$elements[] = 'yolo2';

$container->setParameter('my_param_which_is_array', $elements);
  1. 在您的 services.yaml 文件中导入“my_config.php”,如下所示:
imports:
- { resource: my_config.php }
  1. 清除缓存。
  2. 检查这些参数是否已加载到容器中 - 例如通过运行以下命令:
php bin/console debug:container --parameter=my_param
----------- ------------
Parameter Value
----------- ------------
my_param something1
----------- ------------

php bin/console debug:container --parameter=my_param_which_is_array
------------------------- -------------------
Parameter Value
------------------------- -------------------
my_param_which_is_array ["yolo1","yolo2"]
------------------------- -------------------

如果上述步骤有效,那么您可以在应用程序中使用容器中的参数。

重要警告:如果您将安全凭证存储在此类 php 文件中(数据库用户和密码等),请确保您没有将其与应用程序其余部分的代码一起添加到存储库中 - 所以将它添加到“.gitignore”,类似于在其中添加“.env”。

有关处理 symfony 参数的更多信息,请参阅 https://symfony.com/doc/current/service_container/parameters.html (在代码片段上单击“PHP”选项卡而不是“YAML”以查看 PHP 示例)

第 2 部分 - 根据 url(主机)或 CLI 参数使用不同的数据库

要动态选择数据库连接凭据,我们可以使用 Doctrine 连接工厂。我们将用修改后的版本装饰默认服务 'doctrine.dbal.connection_factory':

创建新文件“src/Doctrine/MyConnectionFactory.php”:

<?php

namespace App\Doctrine;

use Doctrine\Bundle\DoctrineBundle\ConnectionFactory;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\HttpFoundation\Request;

class MyConnectionFactory
{
/**
* @var array
*/
private $db_credentials_per_site;

/**
* @var ConnectionFactory
*/
private $originalConnectionFactory;

public function __construct($db_credentials_per_site, ConnectionFactory $originalConnectionFactory)
{
$this->db_credentials_per_site = $db_credentials_per_site;
$this->originalConnectionFactory = $originalConnectionFactory;
}

/**
* Decorates following method:
* @see \Doctrine\Bundle\DoctrineBundle\ConnectionFactory::createConnection
*/
public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = [])
{
$siteName = $this->getSiteNameFromRequestOrCommand();

if (!isset($this->db_credentials_per_site[$siteName])) {
throw new \RuntimeException("MyConnectionFactory::createConnection - Unknown site name: {$siteName}");
}

return $this->originalConnectionFactory->createConnection(
[
'url' => $this->db_credentials_per_site[$siteName]['url'],
],
$config,
$eventManager,
$mappingTypes
);
}

/**
* @return string
*/
private function getSiteNameFromRequestOrCommand()
{
// If we are inside CLI command then take site name from '--site' command option:
if (isset($_SERVER['argv'])) {
$input = new ArgvInput();
$siteName = $input->getParameterOption(['--site']);

if (!$siteName) {
throw new \RuntimeException("MyConnectionFactory::getSiteNameFromRequestOrCommand - You must provide option '--site=...'");
}

return (string) $siteName;
}

// Otherwise determine site name by request host (domain):
$request = Request::createFromGlobals();
$host = $request->getHost();
switch ($host) {
case 'my-blue-site.local.dev2':
return 'blue_site';
case 'redsite.local.com':
return 'red_site';
}

throw new \RuntimeException("MyConnectionFactory::getSiteNameFromRequestOrCommand - Unknown host: {$host}");
}
}

现在让我们在 services.yaml 中设置装饰:

(您可以在此处阅读有关装饰服务的更多信息:https://symfony.com/doc/current/service_container/service_decoration.html)

    App\Doctrine\MyConnectionFactory:
decorates: doctrine.dbal.connection_factory
arguments:
$db_credentials_per_site: '%db_credentials_per_site%'

并在“config/my_config.php”中添加 'db_credentials_per_site' 参数 - 如您所见,它被注入(inject)到上面的 MyConnectionFactory 中:

$container->setParameter('db_credentials_per_site', [
'blue_site' => [
'url' => 'mysql://user1:pass1@127.0.0.1:3306/dbname-blue',
],
'red_site' => [
'url' => 'mysql://user2:pass2@127.0.0.1:3306/dbname-red',
],
]);

我们还需要一件事来在 CLI 命令中支持此功能 - 我们需要向每个命令添加 '--site' 选项。如您所见,它正在 \App\Doctrine\MyConnectionFactory::getSiteNameFromRequestOrCommand 中读取。所有将使用数据库连接的命令都是强制性的:

在 services.yaml 中:

    App\EventListener\SiteConsoleCommandListener:
tags:
- { name: kernel.event_listener, event: console.command, method: onKernelCommand, priority: 4096 }

创建新文件“src/EventListener/SiteConsoleCommandListener.php”:

<?php

namespace App\EventListener;

use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Input\InputOption;

class SiteConsoleCommandListener
{
public function onKernelCommand(ConsoleCommandEvent $event)
{
// Add '--site' option to every command:
$command = $event->getCommand();
$command->addOption('site', null, InputOption::VALUE_OPTIONAL);
}
}

现在我们准备测试它是否有效:

  • 当您调用 http://my-blue-site.local.dev2/something 时,将使用 'blue_site' 数据库凭证。
  • 当您调用 http://something.blabla.com/something 时,将使用 'red_site' 数据库凭证。
  • 当您运行以下命令时,将使用 'blue_site' 数据库凭证:
php bin/console app:my-command --site=blue_site
  • 当您运行以下命令时,将使用 'red_site' 数据库凭证:
php bin/console app:my-command --site=red_site

关于php - 在 Symfony 中使用 config.php 和 doctrine.yaml 使用动态数据库名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57291092/

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