mollie / mollie-api-php

Mollie API client for PHP
http://www.mollie.com
BSD 2-Clause "Simplified" License
552 stars 191 forks source link

Feature/add auto pagination iterator #701

Closed Naoray closed 11 months ago

Naoray commented 1 year ago

This PR adds new iterator methods which return Generators in order to simply loop over all results from provided by the Mollie API. It takes a similar approach as the basic implementation of the iteration API on the Mollie NodeJS repo.

Essentially all endpoints that extend the CollectionEndpointAbstract and provide a Collection that extends CursorCollection (all that support cursor pagination) have been given iterator() methods (or variations of it). The iterator() methods take the same params as the page() method (or variations of the page method).

Here is an overview of how the iteration methods map to previous existing page like methods:

Basic Usage

// instead of doing
$page = $client->orders->page();

while ($page->hasNext()) {
    foreach ($page as $order) {
        echo($order->id);
    }

    $page = $page->next();
}

// we can now loop over all orders directly
foreach ($client->orders->iterator() as $order) {
    echo($order->id);
}

Backwards looping

// instead of doing
$page = $client->orders->page(’some_order_id');

while ($page->hasPrevious()) {
    foreach ($page as $order) {
        echo($order->id);
    }

    $page = $page->previous();
}

// passing iterateBackwards: true or simply using the fourth param will iterate backwards 
foreach ($client->orders->iterator(iterateBackwards: true) as $order) {
    echo($order->id);
}
fjbender commented 1 year ago

Nice!

Named arguments would require PHP 8.0 though, right? It's just the example you used here, but still worth noting.

Additionally, having those examples in the examples/ directory would be nice IMHO.

Naoray commented 1 year ago

Nice!

Named arguments would require PHP 8.0 though, right? It's just the example you used here, but still worth noting.

Additionally, having those examples in the examples/ directory would be nice IMHO.

@fjbender yes the named arguments is just an example. You could also use the functionality like

foreach ($client->orders->iterator(null, null, [], true) as $order) {
    echo($order->id);
}

I’ve added the code to the examples.