phpsymfonydependency-injectionsymfony5doctrine-dbal

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


I want to configure the Doctrine bundle to have a DBAL connection. For some reason the configuration needs a bit of logic to retrieve. I tried to use a container extension and then a compiler pass to execute the logic while the container is compiled and store the configuration as container parameters.

During my attempts, I registered the extension and compiler pass like this in the Kernel class:

protected function build(ContainerBuilder $container)
{
    // Those lines weren't there at the same time
    $container->registerExtension(new MyCustomExtension());
    $container->addCompilerPass(new MyCustomCompilerPass());
}

It seemed to work well as I could see my parameters in the console:

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

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

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

The problem is that when I try to use those parameters in my config/packages/doctrine.yaml I get an error on my next console command:

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".  
                                                                                

I am using Symfony 5.3 and Doctrine bundle 2.4.


Solution

  • I think the Doctrine bundle configuration gets processed before my compiler pass can declare the parameters. It probably can't be solved using the DependencyInjection component.

    Solved it by importing a PHP configuration file in the services.yaml:

    imports:
        - { resource: my_custom_file.php }
    

    With the following content:

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