Search code examples
phpforeachaws-sdkaws-php-sdk

Pagination in FOREACH loop with OBJECTS from WPS APK


I wrote this code that works pretty well, it retrieves files from nested folder in s3 bucket that change on signed in user changes, provides images from jpg in nested folder using the root folder to create a DIV, and print out infos taken from a CSV stored in the same folder as the images .

$current_user = wp_get_current_user();  
$current_user_nambre = $current_user->user_login;
$dir = 's3://xy/zvx/users/' . $current_user_nambre . '/';

$s3 = new S3Client([
    'region' => 'eu-central-1',
    'profile' => 'default',
    'version' => '1'
]);

$s3->registerStreamWrapper();
$products = new RecursiveDirectoryIterator($dir);
$medias = new RecursiveDirectoryIterator($is_product);
                    foreach ($medias as $is_thumb) 
                    {[...]

It works, and perfectly. But... If it finds too many CSV, it takes too long for the FirstByte and the server automatically quit the request giving the user a time-out page.

What I want to do is to use pagination inside the FOREACH, but it states that I cannot use array_slice for an object...


Solution

  • I managed it working using LimitIterator, it works perfectly.

    $products = new RecursiveDirectoryIterator($dir);
    $limitIterator = new LimitIterator($products, $offset, $limit);
    $n = 0;
    foreach ($limitIterator as $is_product) {
    [...]
    
    
    [...] }
    if ($n == 10) {
        echo '<a href="?offset='.($offset + 10).'">Next</a>';
    

    as seen here on stackoverflow