Przemek
Przemek

Reputation: 6710

Optional parameter value in Symfony's main config.yml

I would like to write something like that in my app's main config.yml:

my_section
  some_value: %local_value%

Where the param local_value would be taken from the parameters_local.yml file. However, I would like this value to be optional - if the application user doesn't provide the local_value parameter in his parameters_local.yml, I would like it to be set to null.

If I leave the config.yml the way I have provided it above and try to omit the local_value from parameters_local.yml, I get the following error message:

[Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException]  
You have requested a non-existent parameter "local_value".

Is there a way around this?

Upvotes: 3

Views: 2243

Answers (1)

Crozin
Crozin

Reputation: 44396

Don't use parameter at all. It's up to the developer to decide what he or she wants to be defined as parameter and what not.

  1. In your configuration define this value as optional:

    $treeBuilder->root('my_section')
        ->children()
            ->scalarNode('some_value')->defaultValue('XYZ')->end()
        ->end()
    ;
    
  2. Let user decide what is most appropriate:

    # config.yml
    my_section: ~
    
    ---
    
    # config.yml
    my_section:
        some_value: ABC
    
    ---
    
    # parameters.yml
    my_section_some_value: 123
    
    # config.yml
    my_section:
        some_value: %my_section_some_value%
    
    ---
    
    # config.yml:
    parameters:
        my_section_some_value: 321
    
    my_section:
        some_value: %my_section_some_value%
    
  3. You application/library SHOULD NOT depend on any of above solutions.

Upvotes: 3

Related Questions