The Singleton Design Pattern falls under creational software design pattern which make sures that there must be only one instance of a class and ensures a single point of access to it. The meaning is if an instance of a class was already created, that existing instance will be returned and used instead of creating a new instance. The singleton design pattern is on of the well-known design patterns that solve the recurring design problems. It helps us how to design flexible and reusable object-oriented application with the aim of making it easier to implement, modify and test.
Below are some application usage of Singleton Design Pattern:
Basic Example:
<?php
class Singleton
{
private static $instance = null;
private function __construct() {}
public static function getInstance(): self
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
}
?>
Example 2:
<?php
class DBConnection
{
private static $instance = null;
private final function __construct() {
echo __CLASS__ . " initialize only once.<br>";
}
public static function getInstance(): self
{
if (null === self::$instance) {
self::$instance = new DBConnection();
}
return self::$instance;
}
}
//create an object of DBConnection class
$conn1 = DBConnection::getInstance();
//create anothe object of DBConnection class
$conn2 = DBConnection::getInstance();
var_dump($conn1 == $conn2);
/* OUTPUT
DBConnection initialize only once.
bool(true)
*/
?>
Example 3: making database connection and fetching records from it
<?php
class DBConnection
{
private static $instance = null;
public $db = null;
private final function __construct()
{
try {
$connection = new PDO('mysql:host=your_host;dbname=your_db', 'your_username', 'your_password');
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db = $connection;
} catch (\PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance(): self
{
if (null === self::$instance) {
self::$instance = new DBConnection();
}
return self::$instance;
}
}
class Product
{
protected $db;
public function __construct()
{
$this->db = DBConnection::getInstance()->db;
}
public function getProducts()
{
$products = [];
$stmt = $this->db->prepare("SELECT * FROM products LIMIT 3");
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) > 0) {
foreach ($result as $row) {
$products[] = array(
'name' => $row['name'],
'mrp' => $row['mrp'],
'discount' => $row['discount'],
'price' => $row['price']
);
}
}
return $products;
}
}
//create an object of Product class
$p = new Product();
$products = $p->getProducts();
print_r($products);
?>
In this easy and simplified tutorial, we are going to learn about most awaited PHP version (PHP 7) and its super important features and enhancements.
An Interface allows you to create programs that specifies which methods a class must implement, without defining how those methods are implemented.
A PHP class that has minimum one abstract method is called as abstract class and cannot be instantiated by itself.