Singleton Design Pattern
Singleton pattern is a creational software design pattern that restricts the instantiation of a class to one “single” instance. This is useful when exactly one object is needed to coordinate actions across the system. It also provides a global endpoint to access the single instance.
For example, Let’s make database connection class to have only one instance across the whole system.
<?php declare(strict_types=1); namespace App\Singleton; class DB { private static $instance; private $connection; // private constructor private final function __construct() { // implement connection to database here } public static function getInstance() { if(!isset(self::$instance)) { self::$instance = new DB(); } return self::$instance; } public function getConnection() { return $this->$connection; } } ?>
Let’s write test cases to verify only single instance is created.
<?php declare(strict_types=1); namespace App\Singleton\Tests; require_once './vendor/autoload.php'; use App\Singleton\DB; use PHPUnit\Framework\TestCase; class SingletonTest extends TestCase { public function testSingleton() { $dbObj1 = DB::getInstance(); $dbObj2 = DB::getInstance(); $this->assertEquals($dbObj1, $dbObj2); } public function testIsInstanceOfDB() { $dbObj = DB::getInstance(); $this->assertInstanceOf(DB::class, $dbObj); } }
Execute tests.
$./vendor/bin/phpunit tests/SingletonTest.php PHPUnit 7.5.20 by Sebastian Bergmann and contributors. .. 2 / 2 (100%) Time: 31 ms, Memory: 4.00 MB OK (2 tests, 2 assertions)
Written on March 27, 2021