note 116577 added to language.generators.syntax

From: Date: Fri, 23 Jan 2015 19:03:00 +0000
Subject: note 116577 added to language.generators.syntax
Groups: php.notes 
Request: Send a blank email to php-notes+get-201513@lists.php.net to get a copy of this message
[This comment replaces my previous comment] 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 CachedGenerator { protected $cache = []; protected $generator = null; public function __construct($generator) { $this->generator = $generator; } public function generator() { foreach($this->cache as $item) yield $item; while( $this->generator->valid() ) { $this->cache[] = $current = $this->generator->current(); $this->generator->next(); yield $current; } } } class Foobar { protected $loader = null; protected function loadItems() { foreach(range(0,10) as $i) { usleep(200000); yield $i; } } public function getItems() { $this->loader = $this->loader ?: new CachedGenerator($this->loadItems()); return $this->loader->generator(); } } $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: 82.161.182.63 ---- Manual Page -- http://php.net/manual/en/language.generators.syntax.php Edit -- https://master.php.net/note/edit/116577 Del: integrated -- https://master.php.net/note/delete/116577/integrated Del: useless -- https://master.php.net/note/delete/116577/useless Del: bad code -- https://master.php.net/note/delete/116577/bad+code Del: spam -- https://master.php.net/note/delete/116577/spam Del: non-english -- https://master.php.net/note/delete/116577/non-english Del: in docs -- https://master.php.net/note/delete/116577/in+docs Del: other reasons-- https://master.php.net/note/delete/116577 Reject -- https://master.php.net/note/reject/116577 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#201513) next »