【问题标题】:DependencyInjection in SymfonySymfony 中的依赖注入
【发布时间】:2017-11-21 10:53:57
【问题描述】:

当我们在 symfony 中使用控制台创建一个 bundle 'MyBundle' 时,它会生成类 MyBundleExtension.php 在这个类中我们找到了一个方法'load'

public function load(array $configs, ContainerBuilder $container)
{
    $configuration = new Configuration();
    $config = $this->processConfiguration($configuration, $configs);    
    $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
    $loader->load('services.yml');
}

当我转储参数 $configs 时,结果是数组内的空数组

从哪里注入这个参数,我怎样才能为这个参数添加值?

【问题讨论】:

    标签: php symfony dependency-injection


    【解决方案1】:

    正如 Mert Simsek 提到的,您可以通过在 app/config/config.yml 中添加配置来配置您的包

    您的捆绑包有一个收集此配置的密钥。默认情况下,此键是使用带有此功能的包名称获取的

    \Symfony\Component\DependencyInjection\Extension\Extension::getAlias
    

    但您可以覆盖此函数以在您的扩展程序中定义自定义键。

    默认情况下(来自 getAlias 函数的文档)别名是这样创建的

    * This convention is to remove the "Extension" postfix from the class
    * name and then lowercase and underscore the result
    

    所以在你的情况下只是“我的”。如果你想为这个包添加配置,你的 yml 配置将如下所示:

    my:
        some_config: value
        set_of_configs:
           config1: value1
           config2: value2
    

    在加载方法 $configs 中执行此操作后,您将获得一个数组。您可以使用预定义的类“配置”来验证此配置。您可以在此处的 Symfony 文档中找到有关捆绑配置的更多信息:

    https://symfony.com/doc/current/components/config/definition.html

    希望对你有帮助,

    亚历山德鲁·科索伊

    【讨论】:

      【解决方案2】:

      您应该将变量添加到app/config/config.ymlfile。

      【讨论】:

        猜你喜欢
        • 2019-01-05
        • 2014-09-23
        • 1970-01-01
        • 1970-01-01
        • 2018-03-02
        • 1970-01-01
        • 2012-07-13
        • 2017-01-23
        • 2012-04-23
        相关资源
        最近更新 更多