BehavioralPHPverifiedVerified

Chain of Responsibility Pattern in PHP

Passes a request along a chain of handlers, where each handler decides to process it or pass it to the next handler in the chain.

How to Implement the Chain of Responsibility Pattern in PHP

1Step 1: Define the request and abstract handler

class Request
{
    public function __construct(
        public readonly string $type,
        public readonly mixed $data,
    ) {}
}

abstract class Handler
{
    private ?Handler $next = null;

    public function setNext(Handler $handler): Handler
    {
        $this->next = $handler;
        return $handler;
    }

    public function handle(Request $request): ?string
    {
        if ($this->next !== null) {
            return $this->next->handle($request);
        }
        return null;
    }
}

2Step 2: Implement concrete handlers

class AuthHandler extends Handler
{
    public function handle(Request $request): ?string
    {
        if ($request->type === 'auth') {
            return "AuthHandler processed: {$request->data}";
        }
        return parent::handle($request);
    }
}

class LoggingHandler extends Handler
{
    public function handle(Request $request): ?string
    {
        echo "Logging request: {$request->type}\n";
        return parent::handle($request);
    }
}

class DefaultHandler extends Handler
{
    public function handle(Request $request): ?string
    {
        return "DefaultHandler: no specific handler for {$request->type}";
    }
}

3Step 3: Chain handlers together

$auth = new AuthHandler();
$logging = new LoggingHandler();
$default = new DefaultHandler();

$auth->setNext($logging)->setNext($default);

echo $auth->handle(new Request('auth', 'token123')); // AuthHandler processed
echo $auth->handle(new Request('other', 'data'));     // DefaultHandler

Chain of Responsibility Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Chain of Responsibility Pattern in the Real World

Like a customer support escalation: your call starts with a front-line agent. If they can’t resolve it, they transfer you to a specialist. If the specialist can’t help, it goes to a manager. Each level either handles it or passes it up the chain.