odan / slim4-skeleton

A Slim 4 Skeleton
https://odan.github.io/slim4-skeleton/
MIT License
439 stars 80 forks source link

How to handle data from repository to presentation as JSON for REST API #92

Closed anthonybachour closed 2 years ago

anthonybachour commented 2 years ago

I'm trying to come up with a good way to go from sql database data to json response on a web api.

I want to return product data but with formatted data for a frontend.

My product has pricing that needs to be formatted as well as vendor and category etc.

I want to return something similar

[{
    "id": 123,
    "title": "product1",
    "price": {
        "formatted": "$10",
        "currency": "USD",
        "regular": 2000,
        "sale": 1000,
        "discountFormatted": "50% off"
    },
    "category": {
        "id": 12,
        "title": "category1"
    },
    "vendor": {
        "id": 155,
        "title": "vendor1"
    }
}]

Now I'm wondering should I make a Data object for each part (ProductData, ProductPriceData, ProductVendorData) and then reference them all in ProductData.

And should the formatted parts be prepared in the repository or service classes?

Thank you for your help.

odan commented 2 years ago

In this case, I would fetch the needed records from the database as an array using the Repository methods. Then loop and map this array(s) into the needed data structure (also an array) in a custom Service class. Let the JsonRenderer convert this Domain result into a JSON response.

Edit: This skeleton has been updated. You can find new up2date examples.

anthonybachour commented 2 years ago

Ok so fetch raw data from Repo and then transform it in service class. Would I use multiple data classes and combine them into an array in the service? I appreciate the help!

Example ProductData

odan commented 2 years ago

If you use the results from the repository only in this specific context (service, use case), an extra data class is not needed, because the scope of the data is so small that there is no real benefit to add extra classes for it. Of course, it depends on your specific use case.

odan commented 2 years ago

I just found this video that explains when and how you can / should use DTOs:

Data Transfer Objects - What Are DTOs

There is also this blog post about this topic:

Stop returning arrays, use objects instead

But he also says that:

You should also consider returning an array if the call is solely internal (between protected methods, for example); value objects should be used for external calls, but arrays are perfectly suitable for internal calls.

This is how I do it in practice as well. I prefer to return arrays from a repositories' method (for a list of records), but if I want to carry data over multiple places I prefer to use objects (DTO's) instead.

I'm closing this issue for now. If you have any further questions, feel free to ask.