Design patterns are reusable solutions to commonly occurring software design problems. They are not frameworks or libraries — they are concepts and code structures you implement yourself. Learning the most common PHP design patterns makes your code more organized, testable, and easier for other developers to understand.
Table of Contents
1. Singleton Pattern
Ensures a class has only one instance and provides a global point of access to it. Most commonly used for database connections, configuration managers, and logging.
class Database {
private static ?Database $instance = null;
private PDO $connection;
private function __construct() {
$this->connection = new PDO(
'mysql:host=localhost;dbname=myapp;charset=utf8mb4',
$_ENV['DB_USER'],
$_ENV['DB_PASS'],
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
}
// Prevent cloning and unserialization:
private function __clone() {}
public function __wakeup(): never { throw new \Exception('Cannot unserialize singleton.'); }
public static function getInstance(): static {
if (static::$instance === null) {
static::$instance = new static();
}
return static::$instance;
}
public function getConnection(): PDO {
return $this->connection;
}
}
// Usage — always the same connection instance:
$db1 = Database::getInstance()->getConnection();
$db2 = Database::getInstance()->getConnection();
var_dump($db1 === $db2); // bool(true) — same object
When to use: Database connections, configuration loading, logging. Avoid overusing it — Singletons make code harder to test because they carry global state.
2. Factory Pattern
Creates objects without specifying the exact class to create. The Factory decides which concrete class to instantiate based on input parameters.
interface PaymentGateway {
public function charge(float $amount): bool;
public function refund(string $transactionId): bool;
}
class StripeGateway implements PaymentGateway {
public function charge(float $amount): bool {
// Stripe API call
return true;
}
public function refund(string $transactionId): bool {
// Stripe refund
return true;
}
}
class PayPalGateway implements PaymentGateway {
public function charge(float $amount): bool {
// PayPal API call
return true;
}
public function refund(string $transactionId): bool {
// PayPal refund
return true;
}
}
class PaymentGatewayFactory {
public static function create(string $provider): PaymentGateway {
return match ($provider) {
'stripe' => new StripeGateway(),
'paypal' => new PayPalGateway(),
default => throw new \InvalidArgumentException("Unknown payment provider: $provider"),
};
}
}
// Usage — the calling code does not know which class it gets:
$gateway = PaymentGatewayFactory::create(config('payment.provider'));
$gateway->charge(500.00);
When to use: Creating objects where the specific type is determined at runtime (payment processors, notification channels, storage adapters).
3. Observer Pattern
Defines a one-to-many relationship: when one object (the Subject) changes state, all its dependents (Observers) are notified and updated automatically.
interface Observer {
public function update(string $event, mixed $data): void;
}
interface Subject {
public function subscribe(string $event, Observer $observer): void;
public function notify(string $event, mixed $data): void;
}
class EventEmitter implements Subject {
private array $listeners = [];
public function subscribe(string $event, Observer $observer): void {
$this->listeners[$event][] = $observer;
}
public function notify(string $event, mixed $data): void {
foreach ($this->listeners[$event] ?? [] as $observer) {
$observer->update($event, $data);
}
}
}
class EmailNotifier implements Observer {
public function update(string $event, mixed $data): void {
if ($event === 'user.registered') {
// Send welcome email to $data['email']
error_log("Sending welcome email to: {$data['email']}");
}
}
}
class SlackNotifier implements Observer {
public function update(string $event, mixed $data): void {
error_log("Slack alert: $event for user {$data['name']}");
}
}
// Usage:
$emitter = new EventEmitter();
$emitter->subscribe('user.registered', new EmailNotifier());
$emitter->subscribe('user.registered', new SlackNotifier());
// When a user registers, both observers are notified:
$emitter->notify('user.registered', ['name' => 'Lyndon', 'email' => 'lyndon@example.com']);
Laravel’s event system is an implementation of the Observer pattern. Event::dispatch() is notify(); event listeners are the Observers.
4. Repository Pattern
Abstracts the data layer — controllers interact with Repository interfaces, not directly with database code. This makes it easy to switch data sources and test with mock repositories.
interface UserRepository {
public function find(int $id): ?array;
public function findAll(): array;
public function save(array $data): int;
public function delete(int $id): bool;
}
class MySQLUserRepository implements UserRepository {
public function __construct(private PDO $db) {}
public function find(int $id): ?array {
$stmt = $this->db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}
public function findAll(): array {
return $this->db->query("SELECT * FROM users")->fetchAll(PDO::FETCH_ASSOC);
}
public function save(array $data): int {
$stmt = $this->db->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute([$data['name'], $data['email']]);
return (int) $this->db->lastInsertId();
}
public function delete(int $id): bool {
$stmt = $this->db->prepare("DELETE FROM users WHERE id = ?");
return $stmt->execute([$id]);
}
}
// In tests, use a mock:
class InMemoryUserRepository implements UserRepository {
private array $users = [];
public function find(int $id): ?array { return $this->users[$id] ?? null; }
public function findAll(): array { return $this->users; }
public function save(array $data): int { $id = count($this->users) + 1; $this->users[$id] = $data + ['id' => $id]; return $id; }
public function delete(int $id): bool { unset($this->users[$id]); return true; }
}
5. Strategy Pattern
Defines a family of algorithms, encapsulates each one, and makes them interchangeable. The calling code selects the strategy at runtime.
interface SortStrategy {
public function sort(array $data): array;
}
class BubbleSort implements SortStrategy {
public function sort(array $data): array {
$n = count($data);
for ($i = 0; $i < $n - 1; $i++) {
for ($j = 0; $j < $n - $i - 1; $j++) {
if ($data[$j] > $data[$j + 1]) {
[$data[$j], $data[$j + 1]] = [$data[$j + 1], $data[$j]];
}
}
}
return $data;
}
}
class QuickSort implements SortStrategy {
public function sort(array $data): array {
if (count($data) <= 1) return $data;
$pivot = $data[0];
$left = array_filter(array_slice($data, 1), fn($x) => $x <= $pivot);
$right = array_filter(array_slice($data, 1), fn($x) => $x > $pivot);
return array_merge($this->sort(array_values($left)), [$pivot], $this->sort(array_values($right)));
}
}
class Sorter {
public function __construct(private SortStrategy $strategy) {}
public function setStrategy(SortStrategy $strategy): void { $this->strategy = $strategy; }
public function sort(array $data): array { return $this->strategy->sort($data); }
}
$sorter = new Sorter(new QuickSort());
$sorted = $sorter->sort([3, 1, 4, 1, 5, 9, 2, 6]);
Which Patterns Matter Most for PHP Developers?
| Pattern | Where You’ll See It |
|---|---|
| Singleton | Database connections, config, logging |
| Factory | Service creation, driver selection |
| Observer | Laravel Events, DOM events |
| Repository | Laravel + service-layer architecture |
| Strategy | Payment processing, export formats, cache drivers |
| Decorator | Laravel middleware, PSR-15 |
| Command | Laravel Jobs, Command pattern in CQRS |
Frequently Asked Questions
Do I need to memorize all design patterns?
No. Know the five covered here deeply — they cover the vast majority of real PHP development scenarios. Factory, Observer, and Repository appear throughout Laravel’s codebase; you are already using them whether you know it or not.
Are design patterns only for large applications?
No, but they are most valuable in medium-to-large codebases where the organizational benefits compound. In a 200-line script, applying the Repository pattern adds overhead without benefit. In a 50-file application, it makes the codebase dramatically easier to maintain and test.
Conclusion
Design patterns are a shared vocabulary for PHP developers. When you say “use a Factory here” or “this needs an Observer,” other developers immediately understand the structure you are proposing. The five patterns above — Singleton, Factory, Observer, Repository, Strategy — cover the most common scenarios in professional PHP development and appear throughout Laravel’s source code.
Next Step for Your Project Journey
Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

