Lesson 5 of 6
Design Patterns in PHP - Factory, Singleton, Observer
Design patterns are proven solutions to recurring design problems. PHP implementations of Factory, Singleton, Observer, Strategy, and Decorator appear in every major framework. Recognising patterns in Laravel, Symfony, and your own code is the mark of a senior PHP developer.
Factory, Observer & Strategy in PHP
<?php
declare(strict_types=1);
// ── Factory Method - creates objects without specifying concrete class ──
interface NotifierInterface {
public function send(string $to, string $subject, string $body): void;
}
class EmailNotifier implements NotifierInterface { public function send(string $to, string $subject, string $body): void { mail($to, $subject, $body); } }
class SlackNotifier implements NotifierInterface { public function send(string $to, string $subject, string $body): void { /* Slack API */ } }
class LogNotifier implements NotifierInterface { public function send(string $to, string $subject, string $body): void { error_log("[NOTIFY] to=$to subject=$subject"); } }
class NotifierFactory {
public static function make(string $driver): NotifierInterface {
return match($driver) {
"email" => new EmailNotifier(),
"slack" => new SlackNotifier(),
"log" => new LogNotifier(),
default => throw new InvalidArgumentException("Unknown notifier: $driver"),
};
}
}
$notifier = NotifierFactory::make($_ENV["NOTIFIER_DRIVER"] ?? "email");
$notifier->send("alice@example.com", "Post published", "Your post is live!");
// ── Observer / Event System ────────────────────────────────────
interface EventListenerInterface {
public function handle(object $event): void;
}
class EventDispatcher {
private array $listeners = [];
public function listen(string $eventClass, EventListenerInterface $listener): void {
$this->listeners[$eventClass][] = $listener;
}
public function dispatch(object $event): void {
foreach ($this->listeners[$event::class] ?? [] as $listener) {
$listener->handle($event);
}
}
}
// Events - plain data classes
class PostPublished { public function __construct(public readonly Post $post) {} }
class UserRegistered { public function __construct(public readonly int $userId, public readonly string $email) {} }
// Listeners
class SendWelcomeEmail implements EventListenerInterface {
public function handle(object $event): void {
if ($event instanceof UserRegistered) {
// Send email to $event->email
}
}
}
class SendPublishNotification implements EventListenerInterface {
public function handle(object $event): void {
if ($event instanceof PostPublished) {
// Notify subscribers of $event->post->title
}
}
}
// Wiring
$dispatcher = new EventDispatcher();
$dispatcher->listen(UserRegistered::class, new SendWelcomeEmail());
$dispatcher->listen(PostPublished::class, new SendPublishNotification());
// Firing events - Service dispatches, listeners react
$dispatcher->dispatch(new UserRegistered(42, "alice@example.com"));
// ── Strategy - interchangeable algorithms ─────────────────────
interface SortStrategyInterface {
public function sort(array $items): array;
}
class SortByViews implements SortStrategyInterface { public function sort(array $items): array { usort($items, fn($a,$b) => $b["views"] <=> $a["views"]); return $items; } }
class SortByDate implements SortStrategyInterface { public function sort(array $items): array { usort($items, fn($a,$b) => strcmp($b["created_at"], $a["created_at"])); return $items; } }
class SortByTitle implements SortStrategyInterface { public function sort(array $items): array { usort($items, fn($a,$b) => strcmp($a["title"], $b["title"])); return $items; } }
class PostSorter {
public function __construct(private SortStrategyInterface $strategy) {}
public function setStrategy(SortStrategyInterface $s): void { $this->strategy = $s; }
public function sort(array $posts): array { return $this->strategy->sort($posts); }
}
$sorter = new PostSorter(new SortByDate());
$sorted = $sorter->sort($posts);
// Switch strategy at runtime
if ($req->query("sort") === "views") $sorter->setStrategy(new SortByViews());
$sorted = $sorter->sort($posts);Quick Quiz
Tip
Tip
Practice Design Patterns in PHP Factory Singleton Observer in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Design Patterns in PHP - Factory, Singleton, Observer
Practice Task
Note
Practice Task - (1) Write a working example of Design Patterns in PHP Factory Singleton Observer from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Design Patterns in PHP Factory Singleton Observer is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?