Skip to content

phptailors/singleton-interface

Repository files navigation

PHPUnit Composer Require Checker BC Check Psalm PHP CS Fixer

phptailors/singleton-interface

A PHP Interface for Singletons. See SingletonInterface.

Installation

composer require --dev "phptailors/singleton-interface:^1.0"
composer require --dev "phpunit/phpunit"

Usage

A minimal implementation (example):

<?php

use Tailors\Lib\Singleton\SingletonInterface;
use Tailors\Lib\Singleton\SingletonException;

final class MySingleton implements SingletonInterface
{
    private static ?MySingleton $instance = null;

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

        return self::$instance;
    }

    private function __construct() {}

    private function __clone() {}

    public function __wakeup()
    {
        throw new SingletonException('Cannot unserialize singleton '.self::class);
    }
}

Expected features of a Singleton

A real Singleton in PHP:

  1. Should NOT be extendable (should be final).
  2. Should have a private constructor (__construct()).
  3. Its getInstance() should return a single instance of its class.
  4. Should NOT be cloneable (__clone() should be a private method).
  5. Should always throw Tailors\Lib\Singleton\SingletonException on unserialize() (from __wakeup()).

Testing Singleton behavior

The behavior of a Singleton may be tested using phptailors/singleton-testing.

About

Singleton Interface

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors