首页 > 解决方案 > 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 用户的观点)。

感谢您的帮助。

标签: phpdependency-injectionsymfony5

解决方案


好的,所以我回复自己。

在扩展文件(在我的例子中为 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 专家阅读了我的帖子,请随时告诉我我是否做错了。


推荐阅读