Skip to content

Instantly share code, notes, and snippets.

@rtuin
Last active March 21, 2016 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtuin/8c66daf6537c473bfdc6 to your computer and use it in GitHub Desktop.
Save rtuin/8c66daf6537c473bfdc6 to your computer and use it in GitHub Desktop.
<?php
// Example: Iterate over all resources from a paginated API endpoint
// PHP 5 vs PHP 7
// Both examples iterate over records like this:
foreach (findAll() as $row) {
// Handle $row
}
// PHP 5
function findAll()
{
return getAllFromPage(1, []);
}
function getAllFromPage($pageNumber, $rows)
{
$url = sprintf('?page=%d', $pageNumber);
$response = $this->restClient->query($url); // body is in $responseBody
$results = json_decode($responseBody, true);
foreach ($results['hits'] as $hit) {
$rows[] = new MakeModel($hit['make'], $hit['model']);
}
if ($nextpagehasrecords) {
$rows = $this->getAllFromPage(++$pageNumber, $rows); // $rows can grow HUGE, it's all in memory
}
return $rows;
}
//
// PHP 7
//
function findAll()
{
yield from getAllFromPage(1);
}
function getAllFromPage($pageNumber)
{
$url = sprintf('?page=%d', $pageNumber);
$response = $this->restClient->query($url); // body is in $responseBody
$results = json_decode($responseBody, true);
foreach ($results['hits'] as $hit) {
yield new MakeModel($hit['make'], $hit['model']);
}
if ($nextpagehasrecords) {
yield from $this->getAllFromPage(++$pageNumber); // will yield each row to the caller 1-by-1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment