Classes List

frdl\Flow\LazyIterator

 1 
 2 
 3 
 4 
 5 
 6 
 7 
 8 
 9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
 56 
 57 
 58 
 59 
 60 
 61 
 62 
 63 
 64 
 65 
 66 
 67 
 68 
 69 
 70 
 71 
 72 
 73 
 74 
 75 
 76 
 77 
 78 
 79 
 80 
 81 
 82 
 83 
 84 
 85 
 86 
 87 
 88 
 89 
 90 
 91 
 92 
<?php


namespace frdl\Flow;
/** LazyIterator * from http://php.net/manual/de/language.generators.syntax.php * CachedGenerator => LazyIerator * (c) 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: * * * * 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"; } */
/* function fibonacci($item) { $a = 0; $b = 1; for ($i = 0; $i < $item; $i++) { yield $a; $a = $b - $a; $b = $a + $b; } } $fibo = fibonacci(10); $list= $fibo; function loadItems($list) { foreach ($list as $value) { yield $value; } } $iterator = new LazyIterator(loadItems($list))->generator(); foreach($iterator as $i) { print $i . "\n"; if( $i == 5 ) { break; } } foreach($iterator as $i) { print $i . "\n"; } */

class LazyIterator {
    protected $cache = [];
    protected $generator = null;
    public function __construct($generator) {
        $this->generator = $generator;
    }
    public function generator() {
        foreach($this->cache as $itemyield ($item);
        while$this->generator->valid() ) {
            $this->cache[] = $current = $this->generator->current();
            $this->generator->next();
            yield ($current);
        }
    }
}