Behavioral Patterns: Strategy, Observer, Command
Model behavior and communication with behavioral patterns.
Modeling behavior
Behavioral patterns govern how objects collaborate and distribute responsibility. We focus on three that appear constantly in real PHP systems:
- Strategy — swap an algorithm at runtime.
- Observer — broadcast events to interested listeners.
- Command — turn a request into an object you can queue, log or undo.
Strategy: the idea
The Strategy pattern defines a family of interchangeable algorithms behind one interface and lets the client choose at runtime. It replaces the sprawling switch below with polymorphism: the context delegates to whichever strategy it holds.
<?php
// The smell Strategy removes: branching on a type code
function price(string $type, float $base): float {
switch ($type) {
case 'standard': return $base + 5;
case 'express': return $base + 15;
default: throw new InvalidArgumentException($type);
}
}
echo price('express', 10), PHP_EOL; // 25
All lessons in this course
- SOLID Principles in Practice
- Creational Patterns: Factory, Builder, Singleton
- Structural Patterns: Adapter, Decorator, Facade
- Behavioral Patterns: Strategy, Observer, Command