Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 4, get .env parameter from a controller, is it possible and how?

From symfony 4, I want create a global parameter and get the value of this parameter from a controller.

This parameter is the path of an another app in the server. So, I thinked add the paramerter in the .env file. But how can I get the value of this parameter from a controller?

like image 293
spacecodeur Avatar asked Sep 03 '18 14:09

spacecodeur


People also ask

Where is .env file Symfony?

Instead of defining env vars in your shell or your web server, Symfony provides a convenient way to define them inside a . env (with a leading dot) file located at the root of your project. The . env file is read and parsed on every request and its env vars are added to the $_ENV & $_SERVER PHP variables.

Where can I find .env file?

env file is placed at the base of the project directory. Project directory can be explicitly defined with the --file option or COMPOSE_FILE environment variable.


2 Answers

For Symfony 5

in your .env file

APP_PARAM=paramvaluehere

in your config/services.yaml

parameters:
    app.paramname: '%env(APP_PARAM)%'

in your controller

$this->getParameter('app.paramname');
like image 124
Mayank Tiwari Avatar answered Oct 12 '22 23:10

Mayank Tiwari


If someone is stil looking for a quick fix but not much symfonish,

define your parameter in .env

MY_PARAM='my param value'

and then in controller call it

echo $_ENV['MY_PARAM'];

if you call the varaible in the controller you better define it in the config/services.yaml under parameters section and access it through parameterBag is much symfonish way.

like image 28
Theva Avatar answered Oct 13 '22 00:10

Theva