Answer the question
In order to leave comments, you need to log in
How to load DTO into Entity in Symfony?
Hello.
It was necessary to validate the data from the DTO and I wrote a Resolver that works up to the Controller and interacts with the Request. In it, I injected Serializer (for loading Request data into DTO) and Validator interfaces, respectively.
Next, I needed to load the DTO into Entity and at the same time take into account the possibility that the fields between them may differ.
To do this, I wrote EntityDtoLoader, a kind of persimmon that checks existing set methods and, in case of matches, loads its own:
protected function load($dto, $model)
{
$modelMethods = get_class_methods($model);
$dtoMethods = get_class_methods($dto);
foreach ($dtoMethods as $method) {
preg_match('/get(.*)/', $method, $name);
if (count($name)) {
$name = $name[1];
foreach ($modelMethods as $modelMethod) {
if ($modelMethod === 'set'.$name) {
$model->{'set'.$name}($dto->{'get'.$name}());
}
}
}
}
}
Answer the question
In order to leave comments, you need to log in
In general, it is a bad practice to map on the essence of a DTO.
Why: an entity is some kind of business object, it controls state transitions and encapsulates the logic itself. But the entity is in the context of ... a business process, which is expressed by some other type of class (interactors or use cases, if Bob Martin's terms), for example, in CQRS, this kind of class is command handlers.
Bottom line: it’s probably not worth working with entities directly, especially since there shouldn’t be setters in entities :) and methods for converting data from DTO explicitly aka fromDto(), as Flying pointed out (with all due respect), because this is not business logic , but some transport-application... Static constructors can be, but not for DTO, but for certain data that displays a business opportunity.
In addition, your solution is fraught with high coupling - your entities are constructed for dto, dto for entities ...
How to do it well:
Create entities only as part of a business process, that is, always explicitly and directly through a constructor or factory method that embodies the business -logic.
In vain I wrote EntityDtoLoader?
Or which is better?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question