2012-09-25 10 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'はタイプミスですか? –

9

のSymfony 2.4からは、このための式を使用することができます。

引数を:[ "@ = container.hasParameter( 'some_param') パラメータ( 'some_param'):? 'DEFAULT_VALUEを'"]

さらにhttp://symfony.com/doc/current/book/service_container.html#using-the-expression-language

+0

また、引数を使用することもできます:["@ = parameter( 'some_param')?パラメータ( 'some_param'): 'default_value'"] –