PHP code example of takuya / php-genetator-array-access

1. Go to this page and download the library: Download takuya/php-genetator-array-access 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/ */

    

takuya / php-genetator-array-access example snippets



// generators by yield.
$generator = (function(){foreach (['x'.'y','z'] as $e){ yield $e;}})();
// Using with new.
use Takuya\Php\GeneratorArrayAccess;
$iter = new GeneratorArrayAccess($generator);

// Access as Array. 
$iter[0]; #=> 'x'
$iter[1]; #=> 'y'
$iter[2]; #=> 'z'

class MyClass{
  public function elements(){
    foreach ($this->paths[] as $path){
      yield get_something($path);
    }
  }
}

$node = new MyClass();
// Generator can Access foreach
foreach ($node->elements() as $item) {
  // something.    
}
// but Cannot access as Array
$first = $node->elements()[0]; //=> Error

$node = new MyClass();
$elements = new CachingIterator($node->elements())
// CachingIterator cannot access Directory, before cached.
$first = $elements[1]; //=> BadMethodCallException
// after caching, CachingIterator can access as Array.
foreach ($elements as $e){;;}
$first = $elements[1]; //=> not null.

$node = new MyClass();
$elements = new \CachingIterator(
  $node->elements(),
  \CachingIterator::FULL_CACHE
);// <= All Cached on constructor.


$node = new MyClass();
$iter = new GeneratorArrayAccess($node->elements());
$iter[1]; //=> make cache $iter[0],$iter[1];
$iter[9]; //=> make cache $iter[0]...$iter[9]

$node = new MyClass();
$iter = new GeneratorArrayAccess($node->elements());
// first access 
foreach($iter as $e){;;}
// cache access with rewind.
foreach($iter as $e){;;}

function my_list_items(){
  foreach(  $api->call('list_item') as $id){
    $list[]=$api->call('get_item', $id);
  }
  return $list;
}
$items = $my_list_items();
$item = $items[0];

function my_list_items(){
  foreach(  $api->call('list_item') as $id){
    $item  = $api->call('get_item', $id);
    yield $item;
  }
}
$items = $my_list_items();
$item = $items[0];//<= No Code changed. Becomes ERORR!. 

function my_list_items(){
  return new GeneratorArrayAccess((function(){
  foreach(  $api->call('list_item') as $id){
    $item  = $api->call('get_item', $id);
    yield $item;
  }  
  })());
}
$items = $my_list_items();
$item = $items[0];//<= No Code changed. **No Error**.

$generator = (function(){
  while(true){ yield 'a';}
})();
$iter = new GeneratorArrayAccess($generator);
sizeof($iter);//=> infinite loop
shell
repository='php-generators-into-array-access'
composer config repositories.$repository \
vcs https://github.com/takuya/$repository  
composer 
shell
composer