2012-09-25 25 views
11

我知道我可以为服务添加可选的服务依赖关系。语法是服务的可选参数依赖关系

arguments: [@?my_mailer] 

但我怎么添加可选参数依赖的服务吗?

arguments: [%my_parameter%] 

我试图

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

但他们都不工作,是实现SF2这个功能?

+0

可选参数的好处是什么?参数用于改变环境之间的配置。你可以改变你的环境中的配置,但那不会那么干净。 – Ryan

回答

-2

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

namespace Acme\FooBundle\Services; 

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

并没有注入任何东西。

+1

Symfony会抛出ParameterNotFoundException! –

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 
    ); 
} 

你让你的参数可选给予默认值到“%参数% '

请让我知道你是否有更好的选择。

+0

'$$ config'是一个错字? –