Skip to content

Return responses as a ResultSet object#16

Closed
andyvanee wants to merge 2 commits intovarsitynewsnetwork:masterfrom
andyvanee:master
Closed

Return responses as a ResultSet object#16
andyvanee wants to merge 2 commits intovarsitynewsnetwork:masterfrom
andyvanee:master

Conversation

@andyvanee
Copy link

By returning a ResultSet object, which extends ArrayObject, we are able to return other valuable information about the result without breaking array-like functionality. The additional data attached is the WP-Total and WP-TotalPages headers (addresses #15) as well as the original request.

ArrayObject's should behave exactly the same as the response from json_decode(), with the exception of direct type checking. Although I don't expect type checking the returned data to be common, this could be considered a breaking change because of that.

The tests were modified since the response is no longer just an array. This could also have been rewritten by casting the ResultSet such as:

expect((array) $data)->to->equal(['foo' => 'bar']);

Feel free to suggest naming change or coding style changes if you see them.

andyvanee added 2 commits May 9, 2018 13:03
ResultSet objects provide access to the original request as well as
the total and totalPages headers supplied by the REST API.
@andyvanee
Copy link
Author

Just to clarify this change, the results from the API are no longer the basic array returned from json_decode, but they can still be used in all the ways you would usually use an array (such as iteration and indexing). This adds three properties to the returned object, which exposes some more information about the results:

$posts = $client->posts()->get();

// Iterate through results as usual
foreach ($posts as $post) {
   print_r($post);
}

// Also index, count, sort, and other array-like behaviour
print_r($posts[0]);
echo count($posts);
usort($posts, function($a, $b) {
    //...
});

// Access data that was previously unavailable
echo $posts->total;
echo $posts->totalPages;
print_r($posts->request);

@andyvanee
Copy link
Author

One issue I've found is that my previous comment about usort is not actually correct, as it does issue a warning. The correct usage would be to use the ArrayObject methods such as:

$posts->uasort(function($a, $b) {
    //...
});

See http://php.net/manual/en/arrayobject.uasort.php

@andyvanee
Copy link
Author

Closing due to inactivity...

@andyvanee andyvanee closed this Mar 23, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant