php - Symfony 5 - 如何在服务或控制器中注入捆绑配置文件
问题描述
我实际上正在学习 SF5 的工作原理,并且我有一个关于将配置文件注入服务或控制器的问题。
我创建了一个“AuthenticationBundle”。然后在 config/packages/authentication.yaml 中,我把模块需要的配置都放好了。
authentication:
login : 1234
password : 5678
我还在捆绑包的 DepedencyInjection 存储库中创建了配置(通过 TreeBuilder 解释配置)和扩展文件。
从那里,在加载函数中,我可以看到我的配置文件的内容。
https://symfony.com/doc/current/bundles/extension.html
但是现在,我怎样才能将它注入到 Controller 或 Service 中?文档在这一点上不够清楚(至少对于新的 SF 用户的观点)。
感谢您的帮助。
解决方案
好的,所以我回复自己。
在扩展文件(在我的例子中为 AuthenticationExtension)中,我以这种方式为服务容器设置了一个新参数:
public function load(array $configs, ContainerBuilder $container) : void
{
$configuration = new Configuration();
// merge config
$config = $this->processConfiguration($configuration, $configs);
// define the name of the key to be injected in controller or service
$container->setParameter('authentication', $config);
}
然后,在 services.yaml 文件中,我能够将变量传递给控制器。
App\AuthenticationBundle\Controller\AuthenticationController :
arguments:
$authenticationConfig: '%authentication%' # define the name of the parameter that will be injected into the controller
之后,我只需要在控制器构造函数中检索它们。
public function __construct(array $authenticationConfig)
{
$this->authenticationConfig = $authenticationConfig;
}
希望这可以帮助别人。
如果某些 Syfmony 专家阅读了我的帖子,请随时告诉我我是否做错了。
推荐阅读
- c# - 在一个多行正则表达式中匹配多个不同的行首和行尾
- .net-core - 比较两个字符串列表的函数
- javascript - 如何使用 JS 选项卡 API 以编程方式静音活动浏览器选项卡?
- javascript - Highcharts 时间线重命名系列标签
- flutter - 命令 PhaseScriptExecution 失败,退出代码为非零 Flutter IOS
- c# - c#中如何将参数传递给URL?
- php - 是什么导致了这些字符?
- python - 尝试在序列化程序“UserSerializer”上获取字段“Name”的值时出现 AttributeError
- c - 对 C 中函数和变量的声明与定义感到困惑
- javascript - 当用户使用后退按钮导航到页面时,Safari 桌面不执行 Javascript