使用 .env 动态禁用 Symfony 4 中的网络工具栏和分析器

Dynamically disable the web toolbar and profiler in Symfony 4 using .env

如果 APP_ENVdev,Web 分析器将设置为激活。在我们的登台服务器上就是这样;然而,我们的登台服务器正在 运行 进行安全审核,因此我们需要手动关闭探查器,同时保持 APP_ENV = dev.

这将成功禁用探查器和工具栏:

web_profiler:
    toolbar: false
    intercept_redirects: false

framework:
    profiler: 
      { enabled: false, only_exceptions: false }

但我想使用 .env 来使用我们可以控制的标志来禁用每个。当我尝试时,Symfony 抱怨:

Environment variables "bool:SYMFONY_TOOLBAR" are never used. Please, check your container's configuration.

这让我得到一个答案 here,它声称:

profiler > enabled cannot be set with a runtime env variable, because that controls whether all the profiler services are created in the container (wrapping services whenever needed to be able to profile them). Changing the container entirely cannot be done at runtime (and the value of this boolean config does not end up being set itself anywhere in the container, which is why this error is triggered)

开发人员说 "Use a parameter in a file that is only loaded in dev mode." 但我不知道那是什么意思;那么,我该如何解决呢? (.env 不是必需的,只是理想的)

由于框架加载其环境变量的顺序,无法在 web_profiler.yaml 中使用环境标志。值得庆幸的是,创建一个新环境并不太难或太可怕:

https://symfony.com/doc/4.1/configuration/environments.html#creating-a-new-environment

创建你的环境,将你的新web_profiler.yaml保存在它下面,然后将它添加到bundles.php的相关行;在我的例子中,我的行在添加 staging 环境后是这样的:

Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true, 'staging' => true],