服务的可选参数依赖项

时间:2012-09-25 10:15:35

标签: symfony

我知道我可以为服务添加可选服务依赖项。语法是

arguments: [@?my_mailer]

但是如何为服务添加可选的参数依赖项?

arguments: [%my_parameter%]

我试过

arguments: [%?my_parameter%]
arguments: [?%my_parameter%]

但它们都不起作用,这个功能是否在sf2中实现?

3 个答案:

答案 0 :(得分:10)

从Symfony 2.4中你可以使用表达式:

  

参数:[" @ = container.hasParameter(' some_param')?   参数(' some_param'):' default_value'"]

更多http://symfony.com/doc/current/book/service_container.html#using-the-expression-language

答案 1 :(得分:8)

我认为如果你不传递/设置参数,Symfony会抱怨服务依赖。您希望使参数可选,以便不需要始终在config.yml文件中设置。并且您希望在设置它时使用该参数。

有我的解决方案:

# src/Acme/HelloBundle/Resources/config/services.yml
parameters:
    my_parameter:

services:
    my_mailer:
        class:        "%my_mailer.class%"
        arguments:    ["%my_parameter%"]

然后

# you-bundle-dir/DependencyInjection/Configuration.php

public function getConfigTreeBuilder()
{
    $treeBuilder = new TreeBuilder();

    $rootNode = $treeBuilder->root('you_bundle_ns');

    // This is for wkhtmltopdf configuration
    $rootNode
            ->children()
            ->scalarNode('my_parameter')->defaultNull()->end()
            ->end();

    // Here you should define the parameters that are allowed to
    // configure your bundle. See the documentation linked above for
    // more information on that topic.

    return $treeBuilder;
}

然后

# you-bundle-dir/DependencyInjection/YourBundleExtension.php

public function load(array $configs, ContainerBuilder $container)
{
    $configuration = new Configuration();
    $config = $this->processConfiguration($configuration, $configs);

    $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
    $loader->load('services.xml');


    $container->setParameter(
        'you_bundle_ns.your_parameter',
        isset($$config['you_bundle_ns']['your_parameter'])?$$config['you_bundle_ns']['your_parameter']:null
    );
}

通过为'%parameter%'

指定默认值,可以使您的参数成为可选参数

如果您有更好的选择,请告诉我。

答案 2 :(得分:-2)

您是否尝试为参数设置默认值?像这样:

namespace Acme\FooBundle\Services;

class BarService
{
    public function __construct($param = null)
    {
        // Your login
    }
}

而不是注射任何东西。