Skip to content

Instantly share code, notes, and snippets.

@henrikbjorn
Last active December 20, 2015 00:29
Show Gist options
  • Save henrikbjorn/995438e67ab75c8fe243 to your computer and use it in GitHub Desktop.
Save henrikbjorn/995438e67ab75c8fe243 to your computer and use it in GitHub Desktop.
<?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);
<?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';
}
}
<?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