Design Patterns PHP - Chain of responsibility Java

1) What have we at the beginning?

Let's imagine that we have object "Request" which need to be handled somehow.
We created interface "Handler" for this.


class Request
{
    /**
     * @var string
     */
    private $attribute;

    function __construct($attribute)
    {
        $this->attribute = $attribute;
    }

    /**
     * @return string
     */
    public function getAttribute()
    {
        return $this->attribute;
    }

}

interface Handler
{
    public function handleRequest(Request $request);
}

class HandlerA implements Handler
{
    public function handleRequest(Request $request)
    {
        echo 'handlerA doing something with request' . PHP_EOL;
    }
}

class HandlerB implements Handler
{
    public function handleRequest(Request $request)
    {
        echo 'handlerB doing something with request' . PHP_EOL;
    }
}




2) What are we doing in client?

Depending on "attribute" field of Request we choose which "Handler" has to service this request.


$handlerA = new HandlerA();
$handlerB = new HandlerB();

if ($request->getAttribute() == 'handlerA') {
    $handlerA->handleRequest($request);
} else {
    $handlerB->handleRequest($request);
}




3) What are cons?

We want to simplify "Client" we don't want to make "Client" to check "attribute"

Can be more than two "Handler" objects and check "Request" objects shouldn't be responsible of "Client"

4) What can we do?

We apply "ChainOfResponsibility" pattern so:

1) We bind "Handlers" in chain
2) In "Handler" we check if this handler can service "Request"
3) If yes let's service "Request"
4) If not pass "Request" to next "Handler"

Let's see this in step2