note 93118 added to language.oop5.patterns
| From: | edgar at goodforall dot eu | Date: | Mon, 24 Aug 2009 16:39:20 +0000 |
| Subject: | note 93118 added to language.oop5.patterns | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-159830@lists.php.net to get a copy of this message | ||
This class will let you chain objects together into a chain. You can forward a message into the
chain. The message propagates upwards into the chain until an object can handle it and returns a
value. Then the return value is send backwards into the chain until it reached the caller.
This can be useful in various situations, where flexibility is needed.
In the begin of the chain we put more specialized methods, which will handle special cases (like
user defined objects, json code, xml etcetera). And in the back more general (strings,
array's). Now we can pass data to the chain and always get valid and safe html back. If we
encounter a new data type we just put on the head of the chain a new object, which can handle this
type of data.
<?php
abstract class Chainable {
protected $next = null;
protected $prev = null;
protected $res = null;
public function forward(Message $object){
if($return = $this->run($object)){
return $this->backward($return);
}
if($this->next !== null){
return $this->next->forward($object);
} else {
throw new Exception('No object can handle this type');
}
}
public function backward(Message $object){
if($this->prev === null){
return $object;
} else {
return $this->prev->backward($object);
}
}
abstract public function run(Message $object);
public function addLink(Chainable $link){
if($this->next !== null){
$this->next->addLink($link);
} else {
$this->next = $link;
$this->next->setPrevLink($this);
}
return $this;
}
protected function setPrevLink(Chainable $link){
$this->prev = $link;
return $this;
}
}
?>
Also needed the message object:
<?php
class Message {
protected $data;
public function __construct($data){
$this->data = $data;
}
public function getMessage(){
return $this->data;
}
public function setMessage($data){
$this->data = $data;
}
public function __toString(){
return (string)$this->data;
}
}
?>
----
Server IP: 91.199.167.18
Probable Submitter: 92.65.202.82
----
Manual Page -- http://www.php.net/manual/en/language.oop5.patterns.php
Edit -- https://master.php.net/note/edit/93118
Del: integrated -- https://master.php.net/note/delete/93118/integrated
Del: useless -- https://master.php.net/note/delete/93118/useless
Del: bad code -- https://master.php.net/note/delete/93118/bad+code
Del: spam -- https://master.php.net/note/delete/93118/spam
Del: non-english -- https://master.php.net/note/delete/93118/non-english
Del: in docs -- https://master.php.net/note/delete/93118/in+docs
Del: other reasons-- https://master.php.net/note/delete/93118
Reject -- https://master.php.net/note/reject/93118
Search -- https://master.php.net/manage/user-notes.php