PHP code example of tasoft / cached-generator

1. Go to this page and download the library: Download tasoft/cached-generator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tasoft / cached-generator example snippets



$yieldCount = 0;
$gen = function () use(&$yieldCount) {
    $yieldCount++;
    yield "test-user";

    $yieldCount++;
    yield "admin";

    $yieldCount++;
    yield "normal-user";
    
    $yieldCount++;
    yield "root";
    
    $yieldCount++;
    yield "anonymous";
};

foreach ($gen() as $value) {
    echo "$value\n";
}

/** Output:
test-user
admin
normal-user
root
anonymous
*/

echo $yieldCount; // 5

// searching for admin

$yieldCount = 0;
$user = NULL;

foreach ($gen() as $value) {
    if($value == "admin") {
        $user = $value;
        break;
    }
}
if($user)
    echo "Administrator found at iteration $yieldCount.\n";

// Output: Administrator found at iteration 2.

// Now you need information about the root user:
$yieldCount = 0;
$user = NULL;

foreach ($gen() as $value) {
    if($value == "root") {
        $user = $value;
        break;
    }
}
if($user)
    echo "Administrator found at iteration $yieldCount.\n";

// Output: Administrator found at iteration 4.
// As you see, the generator need to restart.
// Of course, you might continue with the same generator, but if the root user came before admin, you'll never get it.



use TASoft\Util\CachedGenerator;

$yieldCount = 0;
$gen = new CachedGenerator(
    (
        function () use(&$yieldCount) {
             $yieldCount++;
             yield "test-user";
         
             $yieldCount++;
             yield "admin";
         
             $yieldCount++;
             yield "normal-user";
             
             $yieldCount++;
             yield "root";
             
             $yieldCount++;
             yield "anonymous";
        }
     ) /* directly call the closure */ ()
);

$yieldCount = 0;
$user = NULL;

foreach ($gen() as $value) {
    if($value == "admin") {
        $user = $value;
        break;
    }
}
if($user)
    echo "Administrator found at iteration $yieldCount.\n";

// Output: Administrator found at iteration 2.

// Now you need information about the root user:
$yieldCount = 0;
$user = NULL;

foreach ($gen() as $value) {
    if($value == "root") {
        $user = $value;
        break;
    }
}
if($user)
    echo "Administrator found at iteration $yieldCount.\n";

// Output: Administrator found at iteration 2.
// It is 2 again because the first two users are cached and the generator is not called.
// After the cache end is reached, the cached generator will continue forwarding to the original generator.