这是我的第一篇文章,所以我会尽量说清楚。
所以我需要在Symfony配置中定义一些常量(在一个.yaml文件中,我想),我知道我可以定义它们,抛出 public const MY_CONST
但这不是我想要的。
我想这是我需要的(第二部分,我没有使用抽象控制器,因为我不在控制器中
https:/symfony.comdoccurrentconfiguration.html#accessing-configuration-parameters。
但我就是不能让它工作。谁能帮帮我,给我一个例子,或者是其他方法?
谢谢大家。
你描述的参数可以在配置中使用,定义为eg.yaml文件。
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.
当我们做一些类似的事情时,这些值就会被注入到servicecontroller函数中。
public function hello(string $apiKey, int $theAnswer, string $helloWorld) {
// do things with $apiKey, $theAnswer and $helloWorld
}
更多细节和例子可以在symfony文档中找到。https:/symfony.comdoccurrentservice_container.html#binding-arguments by name-or-type。
您也可以直接 使用参数将其注入到定义的服务中.
# config/services.yaml
services:
# explicitly configure the service
App\Updates\SiteUpdateManager:
arguments:
$adminEmail: '[email protected]'