@@ -993,6 +993,75 @@ environment variables, with their values, referenced in Symfony's container conf
993
993
# run this command to show all the details for a specific env var:
994
994
$ php bin/console debug:container --env-var=FOO
995
995
996
+ Create Your Own Logic To Load Env Vars
997
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
998
+
999
+ You can implement your own logic to load environment variables in your
1000
+ application if the default behavior doesn't exactly fit your needs. This
1001
+ can be done by implementing the
1002
+ :class: `Symfony\\ Component\\ DependencyInjection\\ EnvVarLoaderInterface `.
1003
+
1004
+ .. note ::
1005
+
1006
+ When using autoconfiguration, implementing the interface is the only
1007
+ required step. Otherwise, you have to manually add the
1008
+ ``container.env_var_loader `` tag to your class. You can learn more about
1009
+ it in :doc: `the dedicated page </service_container/tags >`.
1010
+
1011
+ Let's say you have a JSON file named ``env.json `` containing your environment
1012
+ variables:
1013
+
1014
+ .. code-block :: json
1015
+
1016
+ {
1017
+ "vars" : {
1018
+ "APP_ENV" : " prod" ,
1019
+ "APP_DEBUG" : false
1020
+ }
1021
+ }
1022
+
1023
+ We can create a new class named ``JsonEnvVarLoader `` to populate our environment
1024
+ variables from the file::
1025
+
1026
+ namespace App\DependencyInjection;
1027
+
1028
+ use Symfony\Component\DependencyInjection\EnvVarLoaderInterface;
1029
+
1030
+ class JsonEnvVarLoader implements EnvVarLoaderInterface
1031
+ {
1032
+ private const ENV_VARS_FILE = 'env.json';
1033
+
1034
+ public function loadEnvVars(): array
1035
+ {
1036
+ $fileName = __DIR__.\DIRECTORY_SEPARATOR.self::ENV_VARS_FILE;
1037
+ if (!is_file($fileName)) {
1038
+ // throw an error or just ignore this loader, depending on your needs
1039
+ }
1040
+
1041
+ $content = json_decode(file_get_contents($fileName), true);
1042
+
1043
+ return $content['vars'];
1044
+ }
1045
+ }
1046
+
1047
+ That's it! Now the application will look at a ``env.json `` file in the
1048
+ current directory to populate environment variables, additionally to the
1049
+ already existing ``.env `` files.
1050
+
1051
+ .. tip ::
1052
+
1053
+ If you want an env var to have a value on a certain environment but to fallback
1054
+ on loaders on another environment, assign an empty value to the env var for
1055
+ the environment you want to use loaders:
1056
+
1057
+ .. code-block :: bash
1058
+
1059
+ # .env (or .env.local)
1060
+ APP_ENV=prod
1061
+
1062
+ # .env.prod (or .env.local.prod) - this will fallback on the loaders you defined
1063
+ APP_ENV=
1064
+
996
1065
.. _configuration-accessing-parameters :
997
1066
998
1067
Accessing Configuration Parameters
0 commit comments