rrylee
6/10/2016 - 9:43 AM

Generator

Generator

<?php

// basic
function _genetator () {
    yield "one";
    yield "two";
    yield "three";
}

foreach (_genetator() as $value) {
    echo $value, PHP_EOL;
}

/*
one
two
three
*/

// Assign a int size instead of a big size area.
function _range ($length) {
    for ($i = 0; $i < $length; $i ++) {
        yield $i;
    }
}

foreach (_range(10000000) as $value) {
    echo $value, PHP_EOL;
}
/*
0
1
...
*/

// generator key-value
$input = <<<'EOF'
1;PHP;Likes dollar signs
2;Python;Likes whitespace
3;Ruby;Likes blocks
EOF;

function input_parser($input) {
    foreach (explode("\n", $input) as $line) {
        $fields = explode(';', $line);
        $id = array_shift($fields);

        yield $id => $fields;
    }
}

foreach (input_parser($input) as $id => $fields) {
    echo "$id:\n";
    echo "    $fields[0]\n";
    echo "    $fields[1]\n";
}

// read file
function readFileLine($file) {
    $handle = fopen($file, 'r');

    if (! $handle) {
        throw new Exception("Can't read this file");
    }

    while (($line = fgets($handle)) !== false) {
        yield $line;
    }

    if (! feof($handle)) {
        throw new Exception("Error: unecxepted fgets() fails");
    }

    fclose($handle);
}

// send to yield
function loger () {
    while (true) {
        $string = yield;
        echo $string, PHP_EOL;
    }
}

$loger = loger();
$loger->send('one');
$loger->send('two');
$loger->send('three');