PHP Generators

download PHP Generators

of 17

  • date post

    12-Apr-2017
  • Category

    Software

  • view

    109
  • download

    1

Embed Size (px)

Transcript of PHP Generators

  • PHP GENERATors

  • SPOILERAlmost everything you can do with generators can be done with an Iterator

    - Generators are just a handy way to create an iterator- YIELD has the power- Some magic

  • me!Simone Di Maulo

    You can find me at @toretto460

    Software Engineer

    [AdEspresso | [Kataskopeo | [Terravision | [Freelance]]]]

  • ITERAtors

  • interface Iterator extends Traversable

    {

    abstract public mixed current ( void )

    abstract public scalar key ( void )

    abstract public void next ( void )

    abstract public void rewind ( void )

    abstract public boolean valid ( void )

    }

  • lets

  • We need to maintain internal index to track the current and next pointer

    rewind() just resets the index so that current() and next() will work as expected.

    Keys dont have to be numeric!

    Iterator implementation

  • Generators provide an easy way to implement

    simple iterators without the overhead or complexity

    of implementing a class that implements the Iterator interface.

    genera

    tors

  • YIELD

  • function lines($file) {

    $handle = fopen($file, "r");

    while (!feof($handle)) {

    yield trim(fgets($handle));

    }

    fclose($handle);

    }

    $lineReader = lines(__DIR__ . '/test.php');

    var_dump($lineReader);

    // object(Generator)#1 (0) {

    // }

  • lets

  • COROUTINES

  • Coroutines are computer program components that generalize subroutines for non preemptive multitasking, by allowing multiple entry points for suspending and resuming execution at certain locations.

    COROUTINES

  • $gen = call_user_func(function (array $data) {

    foreach ($data as $item) {

    // do something before

    yield $item;

    // do something after

    }

    });

    foreach ($gen as $item) {

    doSomethingWith($item);

    }

    before $item0

    doSomething($item0)

    after $item0

    before $item1

    doSomething($item1)

    after $item1

  • lets

  • Easy to create

    Can be delegatedyield from

    The engine creates an iterator for

    you!

    Just yield the values

  • THANKS!Any questions?