awesomite/iterators

Simulates yield in PHP < 5.5

v0.2.0 2017-01-27 19:46 UTC

README

Codacy Badge Coverage Status Build Status

CallbackIterator

CallbackIterator allows to simulate yield feature from PHP 5.5.

PHP >= 5.5

<?php

function getAllFromDatabase($tableName)
{
    $page = 0;
    $perPage = 1000;
    while ($rows = Db::getRows($tableName, $page, $perPage)) {
        foreach ($rows as $row) {
            yield $row;
        }
        $page++;
    }
}

PHP < 5.5

<?php

use Awesomite\Iterators\CallbackIterator;

function getAllFromDatabase($tableName)
{
    $page = 0;
    $perPage = 1000;
    $rows = [];

    return new CallbackIterator(function () use (&$rows, $tableName, &$page, $perPage) {
        if (!$rows) {
            $rows = Db::getRows($tableName, $page, $perPage);
            $page++;
        }

        if ($rows) {
            return array_shift($rows);
        }

        CallbackIterator::stopIterate();
    });
}