@@ -1009,6 +1009,74 @@ environment variables, with their values, referenced in Symfony's container conf
1009
1009
# run this command to show all the details for a specific env var:
1010
1010
$ php bin/console debug:container --env-var=FOO
1011
1011
1012
+ Creating Your Own Logic To Load Env Vars
1013
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1014
+
1015
+ You can implement your own logic to load environment variables if the default
1016
+ Symfony behavior doesn't fit your needs. To do so, create a service whose class
1017
+ implements :class: `Symfony\\ Component\\ DependencyInjection\\ EnvVarLoaderInterface `.
1018
+
1019
+ .. note ::
1020
+
1021
+ If you're using the :ref: `default services.yaml configuration <service-container-services-load-example >`,
1022
+ the autoconfiguration feature will enable and tag thise service automatically.
1023
+ Otherwise, you need to register and :doc: `tag your service </service_container/tags >`
1024
+ with the ``container.env_var_loader `` tag.
1025
+
1026
+ Let's say you have a JSON file named ``env.json `` containing your environment
1027
+ variables:
1028
+
1029
+ .. code-block :: json
1030
+
1031
+ {
1032
+ "vars" : {
1033
+ "APP_ENV" : " prod" ,
1034
+ "APP_DEBUG" : false
1035
+ }
1036
+ }
1037
+
1038
+ You can define a class like the following ``JsonEnvVarLoader `` to populate the
1039
+ environment variables from the file::
1040
+
1041
+ namespace App\DependencyInjection;
1042
+
1043
+ use Symfony\Component\DependencyInjection\EnvVarLoaderInterface;
1044
+
1045
+ final class JsonEnvVarLoader implements EnvVarLoaderInterface
1046
+ {
1047
+ private const ENV_VARS_FILE = 'env.json';
1048
+
1049
+ public function loadEnvVars(): array
1050
+ {
1051
+ $fileName = __DIR__.\DIRECTORY_SEPARATOR.self::ENV_VARS_FILE;
1052
+ if (!is_file($fileName)) {
1053
+ // throw an exception or just ignore this loader, depending on your needs
1054
+ }
1055
+
1056
+ $content = json_decode(file_get_contents($fileName), true);
1057
+
1058
+ return $content['vars'];
1059
+ }
1060
+ }
1061
+
1062
+ That's it! Now the application will look for a ``env.json `` file in the
1063
+ current directory to populate environment variables (in addition to the
1064
+ already existing ``.env `` files).
1065
+
1066
+ .. tip ::
1067
+
1068
+ If you want an env var to have a value on a certain environment but to fallback
1069
+ on loaders on another environment, assign an empty value to the env var for
1070
+ the environment you want to use loaders:
1071
+
1072
+ .. code-block :: bash
1073
+
1074
+ # .env (or .env.local)
1075
+ APP_ENV=prod
1076
+
1077
+ # .env.prod (or .env.local.prod) - this will fallback on the loaders you defined
1078
+ APP_ENV=
1079
+
1012
1080
.. _configuration-accessing-parameters :
1013
1081
1014
1082
Accessing Configuration Parameters
0 commit comments