Skip to content

Best Practices for parsing json items to dto #378

Answered by Sammyjo20
thedangler asked this question in Q&A
Discussion options

You must be logged in to vote

Hey @thedangler!

When it comes to parsing lots of items, I tend to return an array in the createDtoFromResponse method and use array_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.

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 Order DTO.

class Order
{
    public function __construct(
        public string $property, // properties...
    )

    public static function fromArray(array $data): self

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@thedangler
Comment options

Answer selected by thedangler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants