Download - PHP Generators

Transcript

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 )

}

let’s

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 don’t 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.”

generators

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) {

// }

let’s

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

let’s

Easy to create

Can be delegatedyield from <expr>

The engine creates an iterator for

you!

Just yield the values

THANKS!Any questions?