Search code examples
symfonysymfony5

Symfony bundle access config value


I am trying to initialize a service using a config value:

<parameters>
    <parameter key="the.binary">CHANGE_THIS</parameter>
</parameters>

<services>
    <defaults public="true" />

    <service id="TheBundle\TheService">
        <argument key="$env" type="string">%kernel.environment%</argument>
        <argument key="$binaryPath" type="string">%the.binary%</argument>
    </service>

</services>

When I debug:

bin/console debug:config mybinary

I can see the config seems to be as I would expect:

mybinary:
    binary: '/opt/somewhere/binary'

How do I get the value from my bundle config into the parameters where CHANGE_THIS is?


Solution

  • Instead of a parameter you would typically just pull the value from your config and modify the service definition:

    class TheExtension extends Extension
    {
        public function load(array $configs, ContainerBuilder $container)
        {
            $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . "/../Resources/config"));
            $loader->load('services.xml');
    
            dump($configs);
            $binary = $configs[0]['binary']; // Cheating a bit, should build a config tree
    
            // Here is where you set the binary path
            $service = $container->getDefinition(TheService::class);
            $service->setArgument('$binaryPath',$binary);
    
        }
    

    Remove the binaryPath line from your services.xml file.