Last active
March 21, 2016 13:05
-
-
Save rtuin/8c66daf6537c473bfdc6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Example: Iterate over all resources from a paginated API endpoint | |
| // PHP 5 vs PHP 7 | |
| // | |
| // 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 | |
| } | |
| } | |
| // 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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment