About this chapter
Creational patterns deal with making objects, and structural patterns with putting them together. Behavioral patterns are about the third thing: how objects talk to each other and who is responsible for what. They give tested answers to questions like "how do I swap an algorithm at runtime?", "how does one object react when another changes?" and "how do I replace a tangle of if/else with something I can extend?"
Each pattern in this chapter attacks a specific kind of messy communication. As with the other chapters, every one comes with a small PHP example and a note on when it earns its keep - and when it's overkill.
Lessons from courses
- 1 Strategy Pattern Learn the Strategy pattern in PHP: put each algorithm behind an interface and pick one at runtime, replacing a growing if/switch and honoring OCP.
- 2 Observer Pattern Learn the Observer pattern in PHP: a subject notifies subscribers when something happens, keeping the event and the reactions loosely coupled.
- 3 Command Pattern Learn the Command pattern in PHP: wrap a request as an object with an execute method to enable queues, logging, retries and undo.
- 4 Template Method Pattern Learn the Template Method pattern in PHP: a base class defines the steps of an algorithm and subclasses fill in the parts that differ.
- 5 State Pattern Learn the State pattern in PHP: give each state its own class so an object changes behavior as its state changes, instead of scattered if/else.
- 6 Chain of Responsibility Pattern Learn the Chain of Responsibility pattern in PHP: pass a request through a chain of handlers until one handles it - the idea behind middleware.
- 7 Iterator and Mediator Patterns Learn the Iterator pattern in PHP: traverse a collection without exposing its internals, plus the Mediator pattern for taming many-to-many coupling.