使用在自定义容器扩展/编译器传递中声明的容器参数配置 Symfony 3rd 方包

Configure Symfony 3rd party bundle with container parameters declared in custom container extension / compiler pass

我想配置 Doctrine bundle 以具有 DBAL 连接。由于某种原因,配置需要一些逻辑来检索。我尝试使用 container extension and then a compiler pass 在编译容器时执行逻辑并将配置存储为 容器参数 .

在我尝试的过程中,我在 Kernel class:

中像这样注册了扩展和编译器传递
protected function build(ContainerBuilder $container)
{
    // Those lines weren't there at the same time
    $container->registerExtension(new MyCustomExtension());
    $container->addCompilerPass(new MyCustomCompilerPass());
}

它似乎运行良好,因为我可以在控制台中看到我的参数:

 # ./bin/console debug:container --parameters

Symfony Container Parameters
============================

 ------------------------------------------------------------- ------------------------------------------------------------------------ 
  Parameter                                                     Value                                                                   
 ------------------------------------------------------------- ------------------------------------------------------------------------ 
 ...
 some.prefix.host                                              some-mariadb-host
 some.prefix.dbname                                            some-database-name
 ...

问题是,当我尝试在 config/packages/doctrine.yaml 中使用这些参数时,我在下一个控制台命令中遇到错误:

doctrine:
    dbal:
        driver: pdo_mysql
        host: '%some.prefix.host%'
        dbname: '%some.prefix.dbname%'
        # ...
# ./bin/console debug:container --parameters

In ParameterBag.php line 98:
                                                                                
  You have requested a non-existent parameter "some.prefix.host".  
                                                                                

我正在使用 Symfony 5.3Doctrine bundle 2.4.

我认为 Doctrine 包配置在我的编译器传递可以声明参数之前得到处理。估计用DependencyInjection组件解决不了。

通过在 services.yaml:

中导入一个 PHP 配置文件解决了这个问题
imports:
    - { resource: my_custom_file.php }

内容如下:

use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return function(ContainerConfigurator $configurator) {
    // My specific logic

    // Saving the configuration as parameters
    $configurator->parameters()->set('some.prefix.host', $host);
    $configurator->parameters()->set('some.prefix.dbname', $dbname);
    // ...
};