Singleton Pattern in PHP ensures a reusable database connection. Prevent multiple connections and instances, reduce overhead, and improve performance!
👉 How to Implement Singleton Pattern in PHP for Database Connection
✅ How to Use the Singleton( সিংগেলটন (Sing-গেল-টন)) Pattern?
👉 Modify your previous Database.php class to follow the Singleton Pattern 👇
✨ Modification Rules
✨ Use a static property to store the connection
🔒 Make the constructor private to prevent creating new instances from outside the class
🛠️ Create a static method getInstance() to access the connection
📌 Apply Singleton Pattern in Database.php
🔄 Modify your existing Database.php and use the following code ⬇️
Database.php
<?php
// Database.php - Singleton Pattern
require_once "Config.php";
class Database {
private static $instance = null;
private $pdo;
private function __construct() {
try {
$dsn = "mysql:host=" . Config::get("host") . ";dbname=" . Config::get("dbname") . ";charset=utf8mb4";
$this->pdo = new PDO($dsn, Config::get("username"), Config::get("password"), [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
} catch (PDOException $e) {
throw new Exception("Database connection failed: " . $e->getMessage());
}
}
public static function getInstance() {
// 1️⃣ Checks if self::$instance is null (i.e., no instance exists).
// 2️⃣ If null, it creates a new Database object (new Database()).
// 3️⃣ If already created, it returns the existing instance instead of creating a new one.
if (self::$instance === null) {
self::$instance = new Database(); // Creates a new Database object and assigns it to self::$instance.
}
return self::$instance;
}
public function getConnection() {
return $this->pdo;
}
}
?>
🔍 test it
singleton.php
<?php
//singleton.php
require_once 'Database.php';
//✅ কিভাবে ব্যবহার করবেন?
//আগে: //$db1 = new Database(); $db2 = new Database(); // নতুন সংযোগ তৈরি হত
//এখন: $db = Database::getInstance()->getConnection(); //এভাবে একটিমাত্র সংযোগ পুনরায় ব্যবহার হবে।
try {
$db1 = Database::getInstance()->getConnection();
$db2 = Database::getInstance()->getConnection();
if ($db1 === $db2) {
echo "✅ Singleton Pattern কাজ করছে! একই সংযোগ পুনরায় ব্যবহার হচ্ছে।";
} else {
echo "❌ Singleton Pattern কাজ করছে না!";
}
/*
echo ($db1 === $db2)
? "✅ Singleton Pattern Successful! The same connection is being reused."
: "❌ Singleton Pattern Failed!";
*/
} catch (Exception $e) {
echo "❌ Error: " . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
}
?>
Config.php
<?php
//Config.php
class Config {
private static array $settings = [
'host' => 'localhost',
'dbname' => 'testdb',
'username' => 'root',
'password' => ''
];
public static function get($key) {
return self::$settings[$key] ?? null;
}
}
?>
Explanation
The __construct() function will be called only when getInstance() is executed for the first time. Here’s the step-by-step execution:
Step-by-Step Execution
$db1 = Database::getInstance()->getConnection();
1️⃣ getInstance() is called on Database.
Since no instance exists yet, it creates a new object of Database.
At this moment, __construct() is automatically called inside the class.
2️⃣ Inside __construct():
A new PDO connection is established and stored in a static property.
__construct() completes execution.
3️⃣ getInstance() returns the same instance of Database.
4️⃣ getConnection() is called on the returned instance,
It returns the existing PDO connection.
What happens on the second call?
$db2 = Database::getInstance()->getConnection();
1️⃣ getInstance() is called again.
But this time, the instance already exists, so __construct() is NOT called again.
It simply returns the existing instance.
2️⃣ getConnection() returns the same PDO connection stored earlier.
Key Concept
✅ __construct() is only called once, when the first instance is created.
✅ Any further calls to getInstance() reuse the existing instance without calling __construct() again. 🚀
self::: 🧑🏫 This is used to access static properties or methods inside the same class.
🏫 Think of it as pointing directly to the class itself, not an object or instance.
$instance: 🗃️ This is a static property.
📦 It stores a single instance of the class in Singleton pattern.
Why use self::$instance?:
🔄 To access the stored instance of the class from within itself.
⚡ This ensures that only one object of that class exists, and it’s reused.
🔹 Benefits of this Update
✨ Call Database::getInstance()->getConnection(); twice and check if only one connection is being created.
🟢 If everything is correct, you have successfully optimized the database connection! 🎉
✔️ No need to call new Database() multiple times
🌟 Only a single connection will be used throughout the program
🔧 Memory & performance will be optimized