Reading external file to configure doctrine in Symfony 5

Viewed 209

I'm looking for a way to have doctrine (in a symfony 5 application) connect with the database details stored in an external XML file (instead of .env). However I can't seem to be finding a solution. Reading the XML file isn't the problem, I just can't find how to pass the parameters on the doctrine.

I've tried to use a doctrine.php file but fails to connect. I've also tried to use a wrapper class and called the parent construct method but it seems it isn't recommended.

Has anybody every managed to achieve something of the sort ?

Thanks !

1 Answers

Symfony lets you add configuration written in php. See https://symfony.com/doc/current/configuration.html#configuration-formats

That allows to do the following:

Import an additional configuration file in services.yaml

imports:
  - { resource: 'my-db-config.php' }

my-db-config.php:

<?php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

function readConfig() {
    $myConfig = '' // read from your xml file
    return $myConfig
}

return static function (ContainerConfigurator $container) {

    $container
        ->parameters()
        ->set('my.param', readConfig());
};

in use your new param in doctrine.yaml

doctrine:
    dbal:
        connections:
            default:
                url: '%my.param%'
Related