14

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

arguments: [@?my_mailer]

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

arguments: [%my_parameter%]

我试过了

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

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

4

3 回答 3

13

在 Symfony 2.4 中,您可以为此使用表达式:

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

更多信息请访问http://symfony.com/doc/current/book/service_container.html#using-the-expression-language

于 2014-10-14T22:56:44.893 回答
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%' 提供默认值来使参数可选

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

于 2013-06-28T01:53:19.120 回答
-2

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

namespace Acme\FooBundle\Services;

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

并且不注射任何东西。

于 2012-09-30T22:30:33.147 回答