PHP code example of kofan / deferred-collection

1. Go to this page and download the library: Download kofan/deferred-collection library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kofan / deferred-collection example snippets


 

$query  = 'SELECT id, name, department FROM my_table';
$result = $mysqli->query($query, MYSQLI_USE_RESULT)
$models = [];

// ... Dummy code ...
while ($record = $result->fetch_assoc()) {
    if ($record['department'] === 'developers') {
        $models[] = new MyModel($record);
    }
}

// ...
if (somethingWrongHappened()) {
    throw new RuntimeException('Error happened!!!');
}
// ...

// ... Somewhere in the view ... //
foreach ($models as $model) {
    echo "<div>{$model->id} - {$model->name}</div>";

    if (isEnough()) {
        break;
    }
}



$collection = new DeferredCollection(function() {
    $query  = 'SELECT id, name, department FROM my_table';
    $result = $mysqli->query($query, MYSQLI_USE_RESULT)

    while ($record = $result->fetch_assoc()) {
        yield $record;
    }
});

// The collection is not going to be executed yet
$collection
    ->matchProperty('department', 'developers')
    ->instantiate(MyModel::class)

// ...
if (somethingWrongHappened()) {
    throw new RuntimeException('Error happened!!!');
}
// ...

// NOW the collection is going to be executed, but only 1 record per time will be processed
// we are not collecting all the records in a single array as it was done before,
// instead of that, Deferred Collection uses generators for all the data manipulations behind the scenes
foreach ($collection as $model) {
    echo "<div>{$model->id} - {$model->name}</div>";

    if (isEnough()) {
        break;
    }
}