varsitynewsnetwork / wordpress-rest-api-client

A Wordpress API client for PHP
77 stars 63 forks source link

Return responses as a ResultSet object #16

Closed andyvanee closed 5 years ago

andyvanee commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

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 commented 5 years ago

Closing due to inactivity...