-
-
Save henrikbjorn/995438e67ab75c8fe243 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$handlers = array( | |
new SecondInvokerFactory, | |
new SecondSecondInvokerFactory, | |
); | |
function create_chain($invoker, $factory) { | |
return $factory($invoker); | |
} | |
$chain = array_reduce(array_reverse($handlers), 'get_chain', new Invoker); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface Handler | |
{ | |
public function handle($object); | |
} | |
class ChainCallable | |
{ | |
protected $callables; | |
public function add(callable $callable) | |
{ | |
array_unshift($this->callables, $callable); | |
} | |
public function __invoke(Handler $handler) | |
{ | |
$reducer = function (Handler $handler, callable $callable) { | |
return $callable($handler); | |
}; | |
return array_reduce($this->callable, $reduce, $handler); | |
} | |
} | |
class EchoHandler implements Handler | |
{ | |
public function handle($object) | |
{ | |
echo time(); | |
} | |
} | |
class AroundHandler implements Handler | |
{ | |
protected $next; | |
public function __construct(Handler $next) | |
{ | |
$this->next = $next; | |
} | |
public function handle($object) | |
{ | |
echo 'before'; | |
$this->next->handle($object); | |
echo 'after'; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$chain = new ChainCallable; | |
$chain->add(function ($next) { | |
return new AroundHandler($next); | |
}); | |
$handler = $chain(new EchoHandler); | |
// will print "before 2323232323 after" | |
$handler->handle(new \stdClass); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment