Search code examples
phpchain-of-responsibility

Chain of Responsibility implementation


I have implemented Chain of Responsibility pattern in PHP with multiple handlers. As pattern suggests, I can chain handlers as following:

$handler = new Handler();
$handler->chainNext(new HandlerOne)->chainNext(new HandlerTwo)->chainNext(new HandlerThree);
$result = $handler->handle();

I would like to do this in a more programmatic way, but I'm failing to achieve the same. When storing handlers in an array, only the first and the last handler get handled (executed).

$handler = new Handler();
foreach ($handlers as $element) {
    $handler->chainNext(new $element);
}
$result = $handler->handle();

Do you have any suggestions how to this programmaticaly? The main reason to do this: I will never know how many handlers will need to be executed (1..n). I need this to be dynamic, as they will be read from database.


Solution

  • You need the $element on the next loop. Like this:

    $handler = new Handler();
    $last = $handler;
    foreach ($handlers as $element) {
        $last->chainNext($element);
        $last = $element;
    
    }
    $result = $handler->handle();
    

    Code assumes, that $handlers already contains object instances (new $element is wrong then..)