Abstract Class / Interface – Can’t find a way to Model out the API to deserialize the response according to the endpoint

What I want:

I try to deserialize the response from consuming an API Call in PHP. For my endpoints I like to have a Model, that way the Serializer can do it’s magic.

The response:

    "count": 123,
    "next": "string",
    "previous": "string",
    "limit": 123,
    "offset": 123,


Now, every response comes with the same "Base" attributes: count, limit, offset… etc. And then within the results each result is specific for the endpoint.

For Example:

    "id": 0,
    "name": "string",
    "handle": "string"

In Symfony I call the following:

$this->serializer->deserialize($data, EndpointModel::class, 'json')

which should give me:

AppApiModelBaseModel {#541 ▼
  -count: 901
  -limit: 10
  -offset: 0
  -results: array:10 [▼
    0 => AppApiModelEndpointModel {#547 ▼
      -id: 3203
      -name: FooBar
    1 => AppApiModelResultModel {#549 ▶}

Where I’m stuck:

I created the BaseModel.php: https://hastebin.com/exagaworez.xml
And I have the EndpointModel.php: https://hastebin.com/tijinojixo.xml
So I call it with:

$this->serializer->deserialize($data, BaseModel::class, 'json')  

This works just fine, but it only works for the one Endpoint. What I want to have is a Model for every Endpoint and call it somehow with the serializer so it converts my response.

How could I achieve something like that?

Since I need to describe the Endpoint also in the BaseModel it limits me to one Endpoint. I could just duplicate the code over and over to achieve my goal, but that seems bad.

I use Symfony, consume an API with http_client and want to transform the response with the serializer. Maybe someone can point me in the right direction or give me something to read 🙂

Thank you in advance! Let me know if you need more information

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *