Best Practices for parsing json items to dto #378
-
Hello, I'm looking for a better place to place the logic and the json response is also coming from a webhook in the same structure. I haven't seen an example on how to turn large json response to dto. Should I have a DTO for single Order and a DTO for Orders? Regards |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey @thedangler! When it comes to parsing lots of items, I tend to return an array in the public function createDtoFromResponse(Response $response): array
{
$items = $response->json(); // Get the array of items
return array_map(function (array $item) {
return Order::fromArray($item);
}, $items);
} This would be how I would write the class Order
{
public function __construct(
public string $property, // properties...
)
public static function fromArray(array $data): self
{
return new self(
property: $data['property']
);
}
} Then when I call Does that help? |
Beta Was this translation helpful? Give feedback.
Hey @thedangler!
When it comes to parsing lots of items, I tend to return an array in the
createDtoFromResponse
method and usearray_map
to convert each item into an individual DTO. This way there's a small amount of code and it becomes an array of DTOs.This would be how I would write the
Order
DTO.