Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function fake_provider($code)
- {
- if ($code==='cat') return 'meow';
- elseif ($code==='dog') return 'woof';
- elseif ($code==='snake') return 'hiss';
- }
- class Req implements ArrayAccess
- {
- public $codes, $completed=false, $result;
- public function __construct(...$codes)
- {
- $this->codes=$codes;
- }
- public function complete()
- {
- while (!$this->completed()) $this->progress();
- }
- public function progress()
- {
- $code=array_pop($this->codes);
- $this->result[$code]=fake_provider($code);
- }
- public function completed() { return empty($this->codes); }
- public function offsetExists($offset) { if ($this->completed()) return array_key_exists($offset, $this->result); else $this->premature_call(); }
- public function offsetGet($offset) { if ($this->completed()) return $this->result[$offset]; else $this->premature_call(); }
- public function offsetSet ( $offset , $value ) { $this->set_is_forbidden(); }
- public function offsetUnset ( $offset ) { $this->set_is_forbidden(); }
- public function premature_call() { throw new Exception('premature req call'); }
- public function set_is_forbidden() { throw new Exception('set is forbidden'); }
- }
- function process_values()
- {
- $need=new Req('cat', 'snake');
- $tries=0;
- echo("phase once\n");
- while (!$need->completed())
- {
- $tries++;
- echo "try #$tries\n";
- yield $need;
- }
- echo("phase two\n");
- yield "cat goes $need[cat] and snake goes $need[snake]";
- }
- for ($gen=process_values(); $gen->valid(); $gen->next())
- {
- $response=$gen->current();
- echo("response is: ".print_r($response, true)."\n");
- if ($response instanceof Req) $response->progress();
- }
- echo('result is: '.print_r($response, true));
- /*
- ----
- Output is:
- phase once
- try #1
- response is: Req Object
- (
- [codes] => Array
- (
- [0] => cat
- [1] => snake
- )
- [completed] =>
- [result] =>
- )
- try #2
- response is: Req Object
- (
- [codes] => Array
- (
- [0] => cat
- )
- [completed] =>
- [result] => Array
- (
- [snake] => hiss
- )
- )
- phase two
- response is: cat goes meow and snake goes hiss
- result is: cat goes meow and snake goes hiss
- */
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement