lundi 8 février 2021

Symfony: how to set static string value inside DTO

In our application, there are services that work with entities and then return DTOs. Most of them are rather simple and contain simplified/calculated data from an entity(-ies). However, there are a couple of specific cases where a full image path is being returned, but the entity has only an image name.

There are two possible solutions to this situation:

  1. DTO is created in service, and that service has an image path injected as a parameter.
  2. DTO would have static function setImagePath(string $path) and then inside a static function fromEntity($myEntity) I would be able to convert from Entity to DTO and add a path to it, all of it encapsulated in DTO itself.

The problem I see with the 1st solution is that I'd need to inject parameters and have createDto() in every service that would be related to that DTO.

However, after playing around implementing the 2nd solution, I don't really see the correct point where I could call \Path\To\Dto::setImage('abc').

I could try setting it in a DI compiler pass, which will be tricky because parameters aren't resolved yet. Alternatively, I could set it in an EventListener's onKernelRequest(), but that just feels like using it in the wrong way.

So, the main question is - what's the correct/best way to set a static parameter to DTO from a parameter in 'parameters.yml'? Or am I overthinking it, and DTOs shouldn't be able to create themselves from Entities?

Aucun commentaire:

Enregistrer un commentaire