2

Until now, I've been using container parameters from an unversioned parameters.yml file to configure some bundles. The parameters where read during the container compilation to determine which services needed to be injected in a service definition.

Today, I'd like to replace the parameters.yml configuration with environment variables, but as they are resolved at runtime, their value is not available when building the container, and the services have to be public afterwards.

Am I missing something here? Is there a clean way to configure services that way?

[edit]

I want to inject a user provider service into MyService depending on whether a mock feature is enabled, and provide a username.

# bundle configuration
my_extension:
    mock:
        enabled:  '%env(MOCK_ENABLED)%'
        provider: '%env(MOCK_PROVIDER)%'
        username: '%env(MOCK_USERNAME)%'
<?php

class MyExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        // here, mock_enabled is an env var placeholder, not a boolean value
        // the condition will thus always resolve to true.
        if ($config['mock_enabled']) {

            // The other two env vars will be evaluated at runtime
            // and I'm ok with that
            $username = $config['mock_username'];
            $provider = new Definition(
                $config['mock_provider'],
                [$config['mock_username']]
            );
        } else {
            $provider = new Reference(InMemoryUserProvider::class, [[]];
        }

        $definition = new Definition(MyService::class);
        $definition->addMethodCall('setProvider', new Reference($provider));
    }
}
miken32
  • 42,008
  • 16
  • 111
  • 154
nniico
  • 239
  • 2
  • 6

0 Answers0