Symfony 4 – .env Variables Not Available

Tags: , , ,



I’m running in to a brick wall here. Everything so far with Symfony 4 has been sunshine and daisies but now I can’t seem to add any environment variables to my project.

In my project root there is the default .env file populated with the usual APP_ENV, APP_SECRET and DATABASE_URL; that’s all great. However, adding any custom variable there doesn’t seem to actually do anything! If I add in ANOTHER_VAR=hello_world, for example, and then run bin/console debug:container --env-vars, it only dumps the APP_SECRET and DATABASE_URL variables. If I run bin/console about, however, it shows me all of the variables inside .env.

I thought it might be a cached variable issue but if I change the value of APP_SECRET and run the console command again, it dumps the changed value but still not my custom variables.

I suspect that the env vars are not available to the container by default but that doesn’t seem right to me (plus it seems somewhat contradictory to what the Symfony docs themselves say).

What do I need to do to register these variables so I can access them inside a Controller, for example?

Answer

As is typical of me, I stumble across the answer within half an hour of getting frustrated and asking for help.

Contrary to how the documentation reads, simply adding a variable to the .env file does not make it available inside the Container (and so not listed when you run bin/console debug:container --env-vars nor available inside a Controller using $this->getParameter('env(VAR)')). And thinking about it now, this kinda makes sense because you wouldn’t want all of your protected variables available to everything that runs from the Container.

In order to access an env var you need to parameterise it first and this way you can limit access to it as well. Any env vars that you want available to all of your services you can set within the config/services.yaml file like so (assuming autowiring is enabled):

parameters:
   variable_a: '%env(VAR_A)%'

If you would prefer to restrict the env var to just a few services, then you can inject it in to your service as an argument within config/services.yaml like so:

services:
  AppServiceFoo:
    arguments:
      $bar: '%env(BAZ)%'

With the parameter set up like the above, I can now access that env var inside my Controller with $this->getParameter('variable_a'). Running bin/console debug:container --env-vars also outputs it.

It’s a bit of a pain since I assumed that simply calling $this->getParameter('env(BAZ)') would do the trick but I suppose it makes sense (there is actually no parameter called env(BAZ)).

Hopefully this helps someone else struggling to wrap their head around this.



Source: stackoverflow