-1

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?

Alex.Barylski
  • 2,843
  • 4
  • 45
  • 68
  • You are trying to create a parameter named 'the.binary' with a value of '/opt/somewhere/binary'? Typically in your DI extension, you would just access your TheService and set the second argument to your configs binary value. No parameter involved. Is there a reason why you need a parameter? – Cerad Jan 17 '21 at 21:01
  • In the DI extension I can `dump($config)` and see the value I want, so thats good. I am not sure how I get that value to the `TheService` __construct() ??? – Alex.Barylski Jan 17 '21 at 21:10

1 Answers1

0

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.

Cerad
  • 48,157
  • 8
  • 90
  • 92
  • I'm just reading another SO post that sort of explains this, thank you for the clarification. Curious, I would keep the %kernel.environment% because it's not a bundle specific configuration? – Alex.Barylski Jan 17 '21 at 21:31
  • 1
    Typically yes, however in many cases you might not have any definition at all in services.xml. Instead of modifying an existing service definition you can create the service definition completely from scratch in the extension. Really your choice. I have seen it done both ways. The docs have examples and the source code has many more though some of the extensions will make your head spin. The MakerExtension for the make bundle is a good place to start. – Cerad Jan 17 '21 at 21:37
  • It's a lot to digest. I've been going over the twig bundle all day...this particular issue had me stumped, thanks again for the help! – Alex.Barylski Jan 17 '21 at 21:41