Design Patterns PHP - Chain of responsibility Java

1) What have we done?

As we said we bind "Handler" objects in chain.
And we pass request to first handler and we don't have to bother of "Request" anymore.


abstract class Handler
{
    /**
     * @var Handler
     */
    protected $handler;

    public function setHandler(Handler $handler)
    {
        $this->handler = $handler;
    }

    public abstract function handleRequest(Request $request);
}

$handler = new HandlerA();
$handlerB = new HandlerB();
$handler->setHandler($handlerB);

$handler->handleRequest($request);




2) Can we improve this?

Yes in "HandlerA" and "HandlerB" the code is duplicated let's try to eliminate this in step3

class HandlerA extends Handler
{
    public function handleRequest(Request $request)
    {
        if ($request->getAttribute() == 'handlerA') {
            echo 'handlerA doing something with request' . PHP_EOL;
        } elseif ($this->handler) {
            $this->handler->handleRequest($request);
        }
    }
}

class HandlerB extends Handler
{
    public function handleRequest(Request $request)
    {
        if ($request->getAttribute() == 'handlerB') {
            echo 'handlerA doing something with request' . PHP_EOL;
        } elseif ($this->handler) {
            $this->handler->handleRequest($request);
        }
    }
}