如何在 Symfony 配置中定义一些 PHP 常量?

How define some PHP constant in the Symfony configuration?

这是我的第一个post,所以我会尽量清楚

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

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

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

但我无法让它工作。任何人都可以通过给我一个例子或其他方法来帮助我吗?

谢谢大家。

您描述的参数可用于定义为例如的配置;

parameters:
    the_answer: 42

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

绑定参数(推荐):

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

值的范围可以从简单的标量值到服务、.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.

然后当我们做类似的事情时,这些会被注入到 service/controller 函数中:

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'