F
F
ff0xff2020-01-17 15:54:10
symfony
ff0xff, 2020-01-17 15:54:10

Is it possible to change yml config file in symfony 4 with code?

Good time of the day, I have a yml config in my project which, for example, lies here

./config/packages/dev/parameters.yml

The content in it is:
parameters:
    var1: 'data1'
    var2: 'data2'

In symfony itself, I very conveniently get the values ​​​​of this config like this
$this->getContainer()->getParameter('var1');
$this->getContainer()->getParameter('var2');

This is cool and convenient - but is it also possible to conveniently add some parameter to this config?
parameters:
    var1: 'data1'
    var2: 'data2'
    var3: 'data3'

I dug up in the source code that there is a setParameter but when using it I get an error
$this->getContainer()->setParameter('var3','data3');

In srcApp_KernelDevDebugContainer.php line 1605:
                                                      
  Impossible to call set() on a frozen ParameterBag.

In general, the campaign is not quite right - tell me how you can do it without screwing in a bunch of crutches? I'm sure there are solutions out there.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Romashkan, 2020-01-17
@EvgeniiR

$this->getContainer()

This is not good.
You can edit the configured container in compiler passes
. You don't need to get it anywhere else in the code in principle. No $this->getContainer().
Configure and inject services via configuration - https://symfony.com/doc/current/service_container.... .
Now you are just using the container for other purposes.

S
shude, 2020-01-19
@shude

1. If you are working with symphony 4.1+, then getting configuration parameters should be done using

Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class SomeClass{
    private $params;
    public function __construct(ParameterBagInterface $params)
    {
        $this->params = $params;
    }

    public function someMethod()
    {
        $parameterValue = $this->params->get('parameter_name');
    }
}

2. If you have a need to edit config files dynamically, then most likely you have not successfully designed the application logic. This question can be compared to something like "is it possible to edit css files using code" , the answer is yes, but is it really necessary?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question