Created
November 8, 2011 10:34
-
-
Save muhqu/1347454 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function main() { | |
$limit = 100; | |
$offset = 0; | |
$iter = new NextIteratorCallbackIterator(function() use ($orm, $limit, &$offset) { | |
printf("selecting next bunch at offset %d\n", $offset); | |
$recs = $orm->select($filter, $sorting, $limit , $offset); | |
$offset += $limit; | |
if ($recs) { | |
return new ArrayIterator($recs); | |
} | |
return null; // end reached | |
}); | |
$i=0; | |
foreach ($iter as $key => $value) { | |
printf("%20s : %-20s\n", $key, $value); | |
if (++$i>1000) break; // just to prevent an infinit loop during development | |
} | |
} | |
class NextIteratorCallbackIterator implements Iterator { | |
private $_iterator = null; | |
private $_count = 0; | |
private $_callback; | |
public function __construct($callback) { | |
if (!is_callable($callback)) { | |
throw new Exception(__CLASS__.": callback must be callable"); | |
} | |
$this->_callback = $callback; | |
} | |
public function current() { | |
return $this->_iterator !== null ? $this->_iterator->current() : null; | |
} | |
public function key() { | |
return $this->_iterator !== null ? $this->_iterator->key() : null; | |
} | |
public function next() { | |
$tryNext = ($this->_iterator === null); | |
do { | |
if ($tryNext) { | |
$tryNext = false; | |
$this->_iterator = call_user_func($this->_callback, ++$this->_count); | |
} | |
elseif ($this->_iterator !== null) { | |
$this->_iterator->next(); | |
if ($this->_iterator->valid() == false) { | |
$tryNext = true; | |
} | |
} | |
} while ($tryNext); | |
} | |
public function rewind() { | |
$this->_iterator = call_user_func($this->_callback, $this->_count = 0); | |
} | |
public function valid () { | |
return $this->_iterator !== null; | |
} | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment