A
A
Alexey2017-12-12 03:35:59
PHP
Alexey, 2017-12-12 03:35:59

API php, How to give data correctly?

Hello! I'm making an API and I've run into this problem. It is convenient to operate with all data inside the application with objects and classes. Let's say if this is a user's blog post - this is the class

class BlogPost extends Post{
   // ......
}

There is all the data about the post, title, text, attachments, information about the user who uploaded it, etc.
But after all, I need to give this data through JSON, which means I need to convert objects into an array.
I found similar solutions on the web https://stackoverflow.com/questions/14775/convert-php-object-to-as...
But I have even more questions...
1. I did something wrong, since I had such situation?
The most important question is that when working with the API, sending a request from an external application, it is possible to specify the required fields in the fields parameter. This means that by simply converting the object to an array, I will receive empty data, which, perhaps, was not requested by the client. It turns out that simply converting an object to an array is impossible.
Maybe I should create in each such class (BlogPost, GroupPost, User, Attachment, etc.) a method that will return an array of data according to the requested fields? Those. should it turn out that we first build a query to pull data from the database according to the required fields, and then, when converting to an array of an object, check the required fields again and convert only the parameters we need?
Plz kick in the right direction...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2017-12-12
@alexey-m-ukolov

Desired side: Fractal .

D
DieZz, 2017-12-12
@DieZz

It is best to implement the JsonSerializable interface, like this

class BlogPost extends Post implements JsonSerializable {
    //...

   public function jsonSerialize() {
        return [
            'title' => $this->title,
            'attachments' => $this->attachments,
             ...
        ];
    }
}

then you can easily send a response:
return json_encode($blogPost);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question