facebook/facebook-php-sdk-v4 — pull request #275 by SammyK (2014-11-19 22:30:38+00:00)
Title: [4.1] Added baller pagination

I had to refactor the request/response logic slightly to get this to work. But pagination is super-smart now.

When you hit the `/me/photos` endpoint, you might get a response like this:

```json
{
"data": [
],
"paging": {
"cursors": {
"before": "TRvek9UUXdPRGdsfsdEYzRNelk9",
"after": "TVRTlRvek9UUXsdfdsfBMk5EYzRNelk9"
},
"next": "https://graph.facebook.com/v2.2/1234/photos?pretty=0&after=TVRTlRvek9UUXsdfdsfBMk5EYzRNelk9"
}
}
```

It's easy to just grab the `$.paging.next` value, slap on the access token and app secret proof and you've got the next page results. And with the help of `Facebook\Facebook`, you can paginate like so:

```php
$listOfPhotos = $response->getGraphList();

// Get the next page of results
$nextPageOfPhotos = $fb->next($listOfPhotos);
// Or the previous page of results
$previousPageOfPhotos = $fb->next($listOfPhotos);
```

But what about then you get deeply-embedded pagination data with just the cursors and no URL?

```json
{
"data": [
{
"source": "https://scontent-a.xx.fbcdn.net/foo.jpg",
"likes": {
"data": [
. . .
],
"paging": {
"cursors": {
"before": "NTcwODIzNDE2Mzc3OTU0",
"after": "MTAxNTI0NDAwODEzNjU1MjI="
}
}
},
},
. . .
]
}
```

How do you paginate over the likes? `GraphList` to the rescue! You do it just like you would on the root list:

```php
$listOfPhotos = $response->getGraphList();

// Get the next page of likes for first photo
$nextPageOfLikes = $fb->next($listOfPhotos[0]['likes']);
```

Full example:

```php
$listOfPages = $response->getGraphList();
// Only grab 5 pages
$maxPages = 5;
$pageCount = 0;

do {
echo '

Page #' . $page_count . ':

' . "\n\n";

foreach ($listOfPages as $page) {
var_dump($page->asArray());

$likes = $page['likes'];
do {
echo '

Likes:

' . "\n\n";
var_dump($likes->asArray());
} while ($likes = $fb->next($likes));
}
$pageCount++;
} while ($pageCount < $maxPages && $listOfPages = $fb->next($listOfPages));
```

I added [some documentation](https://github.com/SammyK/facebook-php-sdk-v4/blob/add-pagination/docs/GraphList.fbmd) but it could be expanded on.

I've got another PR ready after this one that adds native [file upload functionality](https://github.com/SammyK/facebook-php-sdk-v4/tree/native-file-upload-support) to both regular and batch requests. Turns out, file uploads have been broken this whole time. Lol. :)