'Symfony 5.4 environmental variables in services.yaml::parameters

Recently I decided to use Symfony 5.4 container in one of the projects to provide some comprehensive DI. It works well as usual, until I tried to use some env vars in services.yaml::parameters section.

Docs state that to bind to an env var I should

# services.yaml
parameters:
  my_var: '%env(SOME_ENV_VAR)%'

and it will be resolved from an env var on first call. Okay. I did it this way and here what I get:

echo $container->getParameter('my_var');
// env_b057c2b619f37f36_SOME_ENV_VAR_222ed306d0932595cbdeada438ccbb2a

I do see SOME_ENV_VAR in both $_SERVER and $_ENV. I also tried Dotenv component to be sure I'm not missing something, but vainly. Any env var turns into this sort of env_{hash}_{VAR_NAME}_{hash} pattern.

I'm not using complete Symfony installation, just some spare components. What I'm missing? Should I manually populate each env var on container build stage?


Container is instantiated as follows:

// $_ENV and $_SERVER already contain `SOME_ENV_VAR` here

require_once __DIR__ . '/vendor/autoload.php';

// `use` statements go here

$containerBuilder = new ContainerBuilder();

$loader = new YamlFileLoader(
  $containerBuilder,
  new FileLocator(implode(DIRECTORY_SEPARATOR, [__DIR__, 'config']))
);

$loader->load('services.yaml');

$containerBuilder->compile();

$container = $containerBuilder;

$my_var = $container->getParameter('SOME_ENV_VAR');

echo $my_var;


Solution 1:[1]

The signature for ContainerBuilder::compile() is:

public function compile(bool $resolveEnvPlaceholders = false)

If you do not pass it true, it won't resolve the environment variables' placeholders.

Additionally, there is an issue with your example.

You are calling:

$my_var = $container->getParameter('SOME_ENV_VAR');

But SOME_ENV_VAR is not a container parameter, but an environment variable. The correct call would be:

$my_var = $container->getParameter('my_var');

The whole thing would be:

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

require_once __DIR__ . '/vendor/autoload.php';

$containerBuilder = new ContainerBuilder();

$loader = new YamlFileLoader(
    $containerBuilder,
    new FileLocator(implode(DIRECTORY_SEPARATOR, [__DIR__, 'config']))
);

$loader->load(__DIR__ . '/services.yaml');

$containerBuilder->compile(true);

$container = $containerBuilder;
$my_var    = $container->getParameter('my_var');

echo $my_var;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 yivi