2012-09-25 58 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'是一個錯字? –