note 116572 added to language.generators.syntax
| From: | info at boukeversteegh dot nl | Date: | Fri, 23 Jan 2015 15:18:47 +0000 |
| Subject: | note 116572 added to language.generators.syntax | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-201508@lists.php.net to get a copy of this message | ||
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";
}
----
Server IP: 72.52.91.14
Probable Submitter: 2001:980:d784:1:f917:a27b:d077:2ac7
----
Manual Page -- http://php.net/manual/en/language.generators.syntax.php
Edit -- https://master.php.net/note/edit/116572
Del: integrated -- https://master.php.net/note/delete/116572/integrated
Del: useless -- https://master.php.net/note/delete/116572/useless
Del: bad code -- https://master.php.net/note/delete/116572/bad+code
Del: spam -- https://master.php.net/note/delete/116572/spam
Del: non-english -- https://master.php.net/note/delete/116572/non-english
Del: in docs -- https://master.php.net/note/delete/116572/in+docs
Del: other reasons-- https://master.php.net/note/delete/116572
Reject -- https://master.php.net/note/reject/116572
Search -- https://master.php.net/manage/user-notes.php