Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
Home/PHP/Design patterns/Chain of Responsibility
PHP

PHP

Pragmatic server-side language that powers a large share of the web.

Paradigm
OOP, procedural, functional features
Typing
Dynamic with gradual typing (strict_types)
Memory
Reference counting + cycle collector
Runs
Zend Engine, bytecode + OPcache, optional JIT
Concurrency
Shared-nothing per request; Fibers (8.1)
Behavioral pattern

Chain of Responsibility

Intent

Passes a request along a chain of handlers; each decides to process it or pass it on.

Problem

Request checks (auth, validation, rate limits, caching) pile up in one huge method.

Solution

Turn each check into a handler linked to the next one; HTTP middleware is the everyday example.

Real-world analogy

Think of it like this

Calling tech support: the voice menu, then an operator, then an engineer. Each one solves the problem or escalates it.

Structure

association / extends implements / depends on
Client 4 «interface» Handler + setNext(h: Handler)+ handle(request) 1 BaseHandler - next: Handler+ handle(request) 2 ConcreteHandlers + handle(request) 3

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Handler — Handler declares the interface common to all handlers.
  2. 2BaseHandler — Base Handler (optional) stores the next handler and forwards by default.
  3. 3ConcreteHandlers — Concrete Handlers decide whether to process a request and whether to pass it on.
  4. 4Client — Client composes the chain once or dynamically, and sends requests to any handler.

Code example

A PHP code sample for Chain of Responsibility is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use Chain of Responsibility when different requests need different processing in unknown order.

Use Chain of Responsibility when handlers must run in a particular order.

Use Chain of Responsibility when the set of handlers changes at runtime.

Pros and cons

Pros

  • Control order of handling
  • Single Responsibility and Open–Closed

Cons

  • Some requests may end unhandled

Relations with other patterns

Check yourself

Check yourself

An HTTP request must pass authentication, rate limiting and validation, and each step can stop it.

Saved in this browser only. Part of Behavioral patterns (0/11).