Skip to main content
paulund

2 min read

#design-patterns #php #oop

Singleton Design Pattern

The Singleton pattern ensures that a class has only one instance and provides global access to that instance.

A common use case is a database connection. Your application does not need to open multiple connections to the database; a single connection is sufficient, and all queries run through it. The Singleton pattern gives you that single connection, reusable from anywhere in the code, without accidentally creating a new one.

Be aware that the Singleton can lead to poor design if overused. It also makes code harder to test unless you reset the instance between tests.

Example

<?php

namespace DesignPatterns\Singleton;

/**
 * The Singleton class exposes a `getInstance` method that either creates
 * the instance on first call or returns the existing one.
 */
class Singleton
{
    /**
     * The Singleton's instance is stored in a static field.
     */
    private static $instance = null;

    /**
     * The constructor is private so that external code cannot create new instances directly.
     */
    protected function __construct() { }

    /**
     * Singletons should not be cloneable.
     */
    protected function __clone() { }

    /**
     * Returns the single instance. Creates it on first call; returns the
     * existing instance on every subsequent call.
     */
    public static function getInstance(): Singleton
    {
        if (self::$instance === null) {
            self::$instance = new static();
        }

        return self::$instance;
    }

    /**
     * Business logic methods
     */
    public function methods()
    {
    }
}

/**
 * Usage: verify that getInstance always returns the same object.
 */
function someCode()
{
    $singleton1 = Singleton::getInstance();
    $singleton2 = Singleton::getInstance();

    if ($singleton1 === $singleton2) {
        echo 'Singleton getInstance returned the same object';
    } else {
        echo 'Singleton getInstance did not return the same object';
    }
}

someCode();

Related notes

  • Adapter Design Pattern

    Learn the Adapter design pattern with practical PHP examples, showing how to make incompatible inter...

  • Bridge Design Pattern

    An explanation of the Bridge design pattern with PHP examples, showing how to decouple an abstractio...

  • Builder Design Pattern

    Learn the Builder design pattern with PHP examples. Covers the Director, Builder, Concrete Builder,...


Newsletter

A weekly newsletter on backend architecture, AI-assisted development, and engineering. No spam, unsubscribe any time.