Design Patterns in PHP: Examples and Application

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Design Patterns in PHP: What They Are and Why You Need Them



Design patterns are proven solutions to typical problems in object-oriented programming. They are not ready-made code, but rather templates that can be adapted to a specific situation. In PHP, patterns are especially useful for creating scalable and maintainable web applications.



In this article, we will cover three main patterns: Singleton, Factory, and Observer. For each, we will provide real PHP examples and explain in which situations they should be used.



Why Study Patterns in PHP?

  • Code simplification — a uniform approach to solving problems.
  • Reusability — patterns are easily adaptable to different projects.
  • Ease of maintenance — code becomes understandable for other developers.
  • Testability — using patterns simplifies writing unit tests.


1. Singleton Pattern



Singleton guarantees that a class has only one instance and provides a global access point to it. In PHP, this is often used for database connections, logging, or configuration.



Example: Database class



<?phpclass Database {    private static ?Database $instance = null;    private PDO $connection;

private function __construct() { // Database connection (SQLite example) $this->connection = new PDO('sqlite:example.db'); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); }

public static function getInstance(): Database { if (self::$instance === null) { self::$instance = new self(); } return self::$instance; }

public function getConnection(): PDO { return $this->connection; }

// Prevent cloning and deserialization private function __clone() {} public function __wakeup() { throw new \\Exception("Cannot unserialize singleton"); }}

// Usage$db = Database::getInstance();$pdo = $db->getConnection();?>


When to use Singleton?

  • When exactly one instance of a class is needed (e.g., database connection).
  • For global access to a resource (logger, cache).
  • In situations where creating multiple instances would lead to conflicts.


Disadvantages: violates the single responsibility principle and complicates testing (creates global state).



2. Factory Pattern



Factory Method defines an interface for creating an object but allows subclasses to change the type of object being created. This is useful when the object type is not known in advance or may change.



Example: Notification factory



<?php// Interface for all notification typesinterface Notification {    public function send(string $message): void;}

// Concrete implementationsclass EmailNotification implements Notification { public function send(string $message): void { echo "Sending email: {$message}"; }}

class SMSNotification implements Notification { public function send(string $message): void { echo "Sending SMS: {$message}"; }}

// Factoryclass NotificationFactory { public static function create(string $type): Notification { return match ($type) { 'email' => new EmailNotification(), 'sms' => new SMSNotification(), default => throw new \\InvalidArgumentException("Unknown type: {$type}"), }; }}

// Usage$notification = NotificationFactory::create('email');$notifica

Blogs

Book Recommendations