note 93133 deleted from language.oop5.patterns by googleguy
| From: | googleguy@php.net | Date: | Tue, 22 Oct 2013 11:16:02 +0000 |
| Subject: | note 93133 deleted from language.oop5.patterns by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-197054@lists.php.net to get a copy of this message | ||
Note Submitter: edgar at goodforall dot eu
----
Example, which shows how the class works:
<?php
/* First we create hunderd numbered chainable classes, which will quadrate the passed integer if the
number of the class is the same as the integer.
*/
for($i = 0; $i < 100; $i++){
$funcs[] = create_function('','class C'.$i.' extends Chainable {
public function run(Message $msg){
$int = $msg->getMessage();
if($int == '.$i.'){
return new Message($int * $int);
}
}
};
return new C'.$i.';
');
}
/* Then we create a function, which will chain the objects together and returns C0.
C0 -> C1 -> C2 -> C3 ... -> C99
*/
function chain($funcs, $c = null){
if($c == null){
$func = array_pop($funcs);
$c = $func();
$init = true;
} else {
$init = false;
}
if(count($funcs) > 0){
$func = array_pop($funcs);
$d = $func();
$c->addLink($d);
chain($funcs, $d);
}
if($init){
return $c;
}
}
/* Create the chain */
$c = chain($funcs);
/* Now we can use the chain to calculate quadrates up to 99
output:
25
No object can handle this type
*/
try {
/* This will forward the new Message(5) to C0 then to C1 until it reaches C5,
which calculates 5 * 5 and then returns new Message(5 * 5) to C4 -> C3 .. ->C0 -> caller
When I enter 100 the chain will fail to process the integer, because there is no C100 class. C99
will throw an exception.
*/
$mesg = $c->forward(new Message(5)); // 25
print $mesg . "\n";
$mesg = $c->forward(new Message(100));
print $mesg . "\n";
} catch(Exception $e) {
print $e->getMessage() . "\n";
}
?>