[英]How define some PHP constant in the Symfony configuration?
这是我的第一篇文章,所以我会尽量清楚
所以我需要在 Symfony 配置中定义一些常量(在 a.yaml 文件中,我猜)我知道我可以定义它们 throw public const MY_CONST
但这不是我想要的。
我想这就是我需要的(第二部分,我没有使用 Abstract controller,因为我不在控制器中)
https://symfony.com/doc/current/configuration.html#accessing-configuration-parameters
但我就是无法让它工作。 任何人都可以通过给我一个例子或其他方式来帮助我吗?
多谢你们。
您描述的参数可以在定义为例如的配置中使用;
parameters:
the_answer: 42
然后,您可以在进一步的配置中使用这些值(例如,见下文)。 或者,如果您想在 controller 中处理这些值,您可以(不再推荐)使用$this->getParameter('the_answer')
来获取值。
这种方法将绑定值,然后您可以通过引用参数在 controller 函数/服务中获取(自动注入)。
这些值的范围可以从简单的标量值到服务、.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.
然后,当我们执行以下操作时,它们会被注入到服务/控制器 function 中:
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中找到
您也可以使用 arguments 将其直接注入到定义的服务中。
# config/services.yaml
services:
# explicitly configure the service
App\Updates\SiteUpdateManager:
arguments:
$adminEmail: 'manager@example.com'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.