【问题标题】:How define some PHP constant in the Symfony configuration?如何在 Symfony 配置中定义一些 PHP 常量?
【发布时间】:2020-10-02 00:07:35
【问题描述】:

这是我的第一篇文章,所以我会尽量清楚

所以我需要在 Symfony 配置中定义一些常量(我猜是在 .yaml 文件中) 我知道我可以定义它们 throw public const MY_CONST 但这不是我想要的。

我想这就是我需要的(第二部分,我没有使用抽象控制器,因为我不在控制器中)

https://symfony.com/doc/current/configuration.html#accessing-configuration-parameters

但我就是无法让它工作。谁能帮助我,给我一个例子,或者其他方式吗?

谢谢大家。

【问题讨论】:

  • 需要定义的信息的性质是什么?它是文件路径还是 api 密钥或类似的东西?我怀疑您需要的是 symfony 的参数或更多与框架无关的 .env 环境变量
  • @Kyrre 它只是一些字符串(将与 sprintf() 一起使用以成为完整的 URL)

标签: php symfony configuration yaml constants


【解决方案1】:

你描述的参数可以在定义为eg的配置中使用;

parameters:
    the_answer: 42

然后,您可以在进一步的配置中使用这些值(例如,请参见下文)。或者,如果您想在控制器中处理这些值,您可以(不再推荐)使用$this->getParameter('the_answer') 来获取值。

绑定参数(推荐):

这种方法将绑定值,然后您可以通过引用参数在控制器函数/服务中获取(自动注入)。

值的范围可以从简单的标量值到服务、.env 变量、php 常量以及配置可以解析的所有其他内容。

# config/services.yaml
services:
    _defaults:
        bind:
            string $helloWorld: 'Hello world!'  # simple string
            int $theAnswer: '%the_answer%'      # reference an already defined parameter.
            string $apiKey: '%env(REMOTE_API)%' # env variable.

然后,当我们执行以下操作时,它们会被注入到服务/控制器函数中:

public function hello(string $apiKey, int $theAnswer, string $helloWorld) {
    // do things with $apiKey, $theAnswer and $helloWorld
}

更多细节和示例可以在 symfony 文档https://symfony.com/doc/current/service_container.html#binding-arguments-by-name-or-type中找到

注入服务(替代)

您也可以直接inject it into the defined service using arguments

# config/services.yaml
services:
    # explicitly configure the service
    App\Updates\SiteUpdateManager:
        arguments:
            $adminEmail: 'manager@example.com'

【讨论】:

  • 完美,教会了我一些新东西!将从此处开始具有约束力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-07
  • 2017-03-15
  • 2011-02-14
  • 2017-04-28
  • 2021-04-11
  • 2015-03-16
  • 2011-02-02
相关资源
最近更新 更多