Reputation: 7783
I am using a few of the Facebook Graph API methods that have pagination successfully using cursor-based pagination, similar to this:
echo '<ul>';
$params = array('limit' => 10);
do {
$groups = (new FacebookRequest(
$session, 'GET', '/me/groups', $params
))->execute()->getGraphObject();
if (null !== $groups->getProperty('paging') && null != $groups->getProperty('paging')->getProperty('next')) {
$params = array('limit' => 10, 'after' => $groups->getProperty('paging')->getProperty('cursors')->getProperty('after'));
} else {
$params = null;
}
foreach ($groups->getProperty('data')->asArray() as $group) {
echo '<li><a href="#" data-group-id="' . $group->id . '" class="group-id">' . $group->name . '</a></li>';
}
} while ($params !== null);
echo '</ul>';
This simple code will grab all the groups of the current user. It checks that the paging
and paging
/next
properties are present and if so uses the cursor
to setup another iteration of the loop. I realise now this could probably have been done better as the cursor isn't always available. When I use the /{group-id}/feed
API endpoint there are the previous and next links but no cursor.
So, how am I supposed to make paginated requests when there is no cursor with the Facebook PHP SDK?
I see other answers suggesting using cURL
or even file_get_contents
to grab the next
and previous
URLs but that seems very silly considering I'm using the PHP SDK here - surely there's a built-in way?
I'm using facebook/php-sdk-v4
with Composer
- there doesn't seem to be the (old?) $facebook->api(...)
functionality availble here either.
Upvotes: 2
Views: 650
Reputation: 31479
Have a look at
There is a method getRequestForNextPage()
in the PHP SDK v4.0.0.
// A FacebookResponse is returned from an executed FacebookRequest
try {
$response = (new FacebookRequest($session, 'GET', '/me'))->execute();
// You can get the request back:
$request = $response->getRequest();
// You can get the response as a GraphObject:
$object = $response->getGraphObject();
// You can get the response as a subclass of GraphObject:
$me = $response->getGraphObject(GraphUser::className());
// If this response has multiple pages, you can get a request for the next or previous pages:
$nextPageRequest = $response->getRequestForNextPage();
$previousPageRequest = $response->getRequestForPreviousPage();
} catch (FacebookRequestException $ex) {
echo $ex->getMessage();
} catch (\Exception $ex) {
echo $ex->getMessage();
}
By looking at the source code at
it just handles the next
property:
return $this->handlePagination('next');
IMHO, using the next
property as a default should be fine, opposed to cursors
. Furthermore, I don't even see a cursors
property when querying a sample group's feed, so this might be obsolete.
References:
Upvotes: 3