Created
May 25, 2021 18:12
-
-
Save frankdejonge/b81fa02c82d69d0bb39b3f9fce81225c to your computer and use it in GitHub Desktop.
Generate use-case: paginated API call example
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 | |
/** | |
* Imagine this is an API call | |
*/ | |
function listPage(int $i): array | |
{ | |
$next = $i >= 9 ? null : $i + 1; | |
return ['cursor' => $next, 'items' => array_fill(0, 5, $i)]; | |
} | |
function listPagedResponse(): Generator | |
{ | |
$i = 0; | |
do { | |
$response = listPage($i); | |
foreach ($response['items'] as $item) { | |
yield $item; | |
} | |
} while ($i = $response['cursor']); | |
} | |
/** | |
* The consumer is not aware we're doing multiple API calls | |
*/ | |
foreach (listPagedResponse() as $item) { | |
var_dump($item); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment