Skip to content
Advertisement

How to pass dynamic values to container in Symfony 5

How passing a dynamic variable from controller to a service? I want manage some istance in the constructor of my service that depend by json value. My service take two parameters in the construct: a service and a variable with the JSON.

For the first one, i have passed it directly in the service.yaml. For the second one, i have some difficult.

In the controller, i get from a API the JSON. But this json it can be null.

JavaScript

I stock the JSON in my .env file, MYJSON=null. This is my service.yaml

JavaScript

So, in my service called ConverterHl7Refacto.php, i have the two parameters in the constructor. I would like manage the istances if the json is empty or non. If i do a dd() of $json, i get ‘%env(MYJSON)’ instead JSON. Why?

JavaScript

Advertisement

Answer

Nothing particularly tricky about the factory concept. A factory is basically used to create an instance of a given type. I did not test the following code so apologies for typos:

JavaScript

You will need to exclude your Converter class from autowire in your services.yaml file. But that should be all you need. No need to explicitly define things like app.converter as autowire will take care of all that.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement