Symfony 6.1中能否用when@结合.env环境变量配置YAML?
Symfony 6.1:基于环境变量启用YAML配置段
when@语法是专门用来匹配Symfony应用环境(比如prod、dev、test)的,没法直接和.env里的变量结合使用,你写的when@%env(bool:do_something)%这种写法不会生效。
要实现「仅当环境变量do_something为true时加载配置段」的需求,有两种靠谱的方案:
方案1:带条件的配置导入
把需要条件加载的配置单独放到一个文件里,然后在主配置文件中通过imports的when条件控制是否加载:
主配置文件(比如config/packages/something.yaml):
something: anotherthing: site: &xyz type: 'abcd' api: 'abcd' imports: - { resource: 'something_conditional.yaml', when: '%env(bool:do_something)%' }
创建config/packages/something_conditional.yaml:
something: anotherthing: onlyifdosomething: <<: *xyz
方案2:直接使用when:表达式
如果不想拆分文件,可以在同一配置文件中用when:表达式(Symfony 5.2+支持):
something: anotherthing: site: &xyz type: 'abcd' api: 'abcd' when: '%env(bool:do_something)%' something: anotherthing: onlyifdosomething: <<: *xyz
这两种方式都会在do_something环境变量为true时,自动合并对应的配置段。
内容的提问来源于stack exchange,提问作者simon_kohl
相关产品推荐
相关产品推荐

