note 116572 deleted from language.generators.syntax by salathe
| From: | salathe@php.net | Date: | Fri, 06 Feb 2015 13:11:20 +0000 |
| Subject: | note 116572 deleted from language.generators.syntax by salathe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-201620@lists.php.net to get a copy of this message | ||
Note Submitter: info at boukeversteegh dot nl
----
You can use generators to do lazy loading of lists. You only compute the items that are actually
used. However, when you want to load more items, how to cache the ones already loaded?
Here is how to do cached lazy loading with a generator:
<?php
class Foobar {
public function loader() {
foreach(range(0,10) as $i) {
usleep(200000);
yield $i;
}
}
public function getItems() {
static $loader = null, $cache = [];
$loader = $loader ?: $this->loadItems();
foreach($cache as $item) yield $item;
while( $loader->valid() ) {
$cache[] = $current = $loader->current();
$loader->next();
yield $current;
}
}
}
$f = new Foobar;
# First
print "First\n";
foreach($f->getItems() as $i) {
print $i . "\n";
if( $i == 5 ) {
break;
}
}
# Second (items 1-5 are cached, 6-10 are loaded)
print "Second\n";
foreach($f->getItems() as $i) {
print $i . "\n";
}
# Third (all items are cached and returned instantly)
print "Third\n";
foreach($f->getItems() as $i) {
print $i . "\n";
}
?>