How to process %kernel.project_dir% from a .env variable?

Viewed 4089

I added this to my .env:

PHOTOS_DIR=%kernel.project_dir%/var/photos

Of course, when I try to retrieve the value of $_ENV['PHOTOS_DIR'], I get the raw string %kernel.project_dir%/var/photos.

But how can I get the value processed by the Symfony config processor, e.g. /my/project/var/photos?

EDIT: I'm aware that it is simply possible to add this in services.yaml:

parameters:
    photos_dir: '%kernel.project_dir%/var/photos'

But I would like to keep important config data in the .env file.

3 Answers

In order to expand %kernel.project_dir%, use %env(resolve:...) in parameters, e.g.:

parameters:
    photos_dir: '%env(resolve:PHOTOS_DIR)%'

Your dotenv does not process the symfony yaml processor parameters.
Delete the %kernel.project_dir% from .env file and in your .yaml you need to bind a parameter like this:

photos_absolute_path: '%kernel.project_dir%%env(PHOTOS_DIR)%'

After that you can get the parameter from your container by the name of photos_absolute_path and it will point to the correct location

Using symfony parameters in .env-files is correct. Symfony will automatically resolve them.

After container will be compiled, you can get the real value if you bind it to a parameter. .env

PHOTOS_DIR=%kernel.project_dir%/var/photos

services.yaml:

parameters:
    photos_dir: '%env(PHOTOS_DIR)%'

Somewhere in your application:

$container->getParameter('photos_dir');
Related