Skip to content

Instantly share code, notes, and snippets.

@frankdejonge
Created May 25, 2021 18:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frankdejonge/b81fa02c82d69d0bb39b3f9fce81225c to your computer and use it in GitHub Desktop.
Save frankdejonge/b81fa02c82d69d0bb39b3f9fce81225c to your computer and use it in GitHub Desktop.
Generate use-case: paginated API call example
<?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