Master PHP Design Patterns: Singleton, Factory, Observer, and Adapter

This article explains four essential PHP design patterns—Singleton, Factory, Observer, and Adapter—detailing their purpose, implementation with code examples, and how they help developers write more maintainable, extensible, and flexible backend applications.

php Courses
php Courses
php Courses
Master PHP Design Patterns: Singleton, Factory, Observer, and Adapter

In advanced PHP development, understanding common design patterns is essential for writing maintainable, extensible, and flexible code. This article introduces four widely used patterns and shows how to implement them in PHP.

Singleton Pattern

The Singleton pattern ensures a class has only one instance. In PHP it can be implemented using static methods and properties.

class Database {
    private static $instance;

    private function __construct() {
        // prevent external instantiation
    }

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

    // ...
}

Making the constructor private prevents external instantiation, and the getInstance method returns the same instance each time.

Factory Pattern

The Factory pattern creates objects based on given parameters. A factory class can encapsulate the creation logic.

interface Shape {
    public function draw();
}

class Circle implements Shape {
    public function draw() {
        // draw circle
    }
}

class Rectangle implements Shape {
    public function draw() {
        // draw rectangle
    }
}

class ShapeFactory {
    public static function create($type) {
        if ($type == 'circle') {
            return new Circle();
        } elseif ($type == 'rectangle') {
            return new Rectangle();
        } else {
            throw new Exception('Invalid shape type.');
        }
    }
}

// Usage
$circle = ShapeFactory::create('circle');
$rectangle = ShapeFactory::create('rectangle');

Observer Pattern

The Observer pattern establishes a one‑to‑many dependency so that when an object changes state, all its dependents are notified. PHP provides SplSubject and SplObserver interfaces.

class User implements SplSubject {
    private $name;
    private $email;
    private $observers;

    public function __construct($name, $email) {
        $this->name = $name;
        $this->email = $email;
        $this->observers = new SplObjectStorage();
    }

    public function attach(SplObserver $observer) {
        $this->observers->attach($observer);
    }

    public function detach(SplObserver $observer) {
        $this->observers->detach($observer);
    }

    public function notify() {
        foreach ($this->observers as $observer) {
            $observer->update($this);
        }
    }

    public function setName($name) {
        $this->name = $name;
        $this->notify();
    }

    public function setEmail($email) {
        $this->email = $email;
        $this->notify();
    }
}

class EmailNotifier implements SplObserver {
    public function update(SplSubject $subject) {
        // send email about name/email change
    }
}

// Example
$user = new User('John Doe', '[email protected]');
$user->attach(new EmailNotifier());
$user->setName('Jane Doe');
$user->setEmail('[email protected]');

Adapter Pattern

The Adapter pattern converts one interface into another compatible one. In PHP an adapter class can implement the target interface and delegate calls to the adaptee.

interface Csv {
    public function outputCsv($data);
}

class CsvWriter implements Csv {
    public function outputCsv($data) {
        // output CSV
    }
}

interface Json {
    public function outputJson($data);
}

class JsonWriter implements Json {
    public function outputJson($data) {
        // output JSON
    }
}

class CsvToJsonAdapter implements Json {
    private $csvWriter;

    public function __construct(Csv $csvWriter) {
        $this->csvWriter = $csvWriter;
    }

    public function outputJson($data) {
        $csvData = implode(',', $data);
        $json = json_encode($csvData);
        return $json;
    }
}

// Usage
$csvWriter = new CsvWriter();
$jsonWriter = new CsvToJsonAdapter($csvWriter);

By combining these patterns as needed, developers can solve specific problems and produce higher‑quality PHP code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Design PatternsSingletonAdapterFactoryObserver
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.