Type to search...

Iterate response with SDK

Response

In case the content of response won’t fit on one page, it will be split into pages and page token will be used for navigation. With this SDK feature the response content will be automatically iterated.

Usage

Get iterator object

The iterator object is accessible from the service that we want to use for the API request. For example, if we want to iterate the cloud list, we will need to get our object from the cloud service. In our example we will itarate the image index API response.

$indexParams = new \shardimage\shardimagephp\models\image\IndexParams(['maxResults' => 10]);
$imageIterator = $client->getImageService()->indexIterator()->withParams(['cloudId' => '<cloudId>'])->withIndexParams($indexParams); // parameters are based on normal listing
$cloudIterator = $client->getCloudService()->indexIterator()->withIndexParams(['maxResults' => 10]); // example how we can instantiate a cloud iterator

Rate Limit

With the withRateLimitTrap function it’s possible to handle rate limitation cases.

$func = function ($ex, $imageIterator) {    // optional
    // code
};
$imageIterator = $imageIterator->withRateLimitTrap($func);

Finishing steps

foreach ($imageIterator as $model) {
    // $model is the iterated object, since we used `getImageService` to construct our iterator, it's an image object.
    if ($model instanceof Image) {
        echo $imageIterator->key() . " -> $model->publicId\n";
    }
}
// the while loop won't run because we already finished the iteration in the foreach loop
while ($imageIterator->valid()) {
    $image = $imageIterator->current();
    if ($image instanceof Image) {
        echo $imageIterator->key() . " -> $model->publicId\n";
    }
    $imageIterator->next();
}
$iterator->rewindAll(); // let's start over
// now it will be run again
while ($iterator->valid()) {
    $image = $imageIterator->current();
    if ($image instanceof Image) {
        echo $imageIterator->key() . " -> $model->publicId\n";
    }
    $imageIterator->next();
}
Table of contents