From 6208bed58a9265a4f189cf60c8471be3d052c58b Mon Sep 17 00:00:00 2001 From: Dominik Liebler Date: Sat, 27 Aug 2011 10:05:33 +0200 Subject: [PATCH] added chain of responsibilities pattern --- .../ChainOfResponsibilities.php | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 ChainOfResponsibilities/ChainOfResponsibilities.php diff --git a/ChainOfResponsibilities/ChainOfResponsibilities.php b/ChainOfResponsibilities/ChainOfResponsibilities.php new file mode 100644 index 0000000..d8639fc --- /dev/null +++ b/ChainOfResponsibilities/ChainOfResponsibilities.php @@ -0,0 +1,90 @@ +_data = $data; + } + + /** + * this class has no next handler, so it MUST be able to handle all requests + * + * @param $key + * @return mixed + */ + public function get($key) + { + return $this->_data[$key]; + } +} + +class FastStorage implements KeyValueStorage +{ + /** + * @var array + */ + protected $_data; + + /** + * the next handler in the chain + * + * @var \DesignPatterns\KeyValueStorage + */ + protected $_nextHandler; + + public function __construct(array $data, KeyValueStorage $nextHandler) + { + $this->_data = $data; + $this->_nextHandler = $nextHandler; + } + + /** + * when this storage gets a "miss", search in next handler + * + * @param $key + * @return mixed + */ + public function get($key) + { + if (true /* miss */) { + // delegate the call to the next handler in the chain + return $this->_nextHandler->get($key); + } + } +} + +// BUILD THE STORAGES AND CHAIN + +$slowStorage = new SlowStorage(array('foo' => 'bar')); +$fastStorage = new FastStorage(array('bar' => 'baz'), $slowStorage); + +$fastStorage->get('foo'); // will be handled by SlowStorage +$fastStorage->get('bar'); // will be handled by FastStorage + +/** + * In this example we could also add a abstract class and extend it to build Fast- and SlowStorage. That class would + * then manage the chain and when the cache hits a "miss", it would check if there is a next handler + */ \ No newline at end of file