This article explains about how to define and use Singleton class in php
Define and use a singleton class in php isn’t that much difficult. To define and use a singleton variable in PHP, you can follow the Singleton design pattern. This pattern ensures that a class has only one instance and provides a global point of access to it. Here’s a step-by-step guide to implementing a singleton in PHP:
Step 1: Define the Singleton Class in php
Create a class with a private static variable to hold the single instance, a private constructor to prevent direct instantiation, and a public static method to get the instance.
class Singleton {
// Hold the class instance.
private static $instance = null;
// The constructor is private to prevent initiation with outer code.
private function __construct() {
// Initialization code here.
}
// The object is created from within the class itself only if the class has no instance.
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new Singleton();
}
return self::$instance;
}
// Example method to demonstrate functionality.
public function doSomething() {
echo "Singleton instance doing something!";
}
}
Step 2: Use the Singleton class in php
To use the singleton, you call the getInstance
method. This ensures that you always get the same instance of the class.
$singleton = Singleton::getInstance();
$singleton->doSomething();
Explanation
- Private Static Variable:
private static $instance
holds the single instance of the class. - Private Constructor:
private function __construct()
prevents direct creation of the object. - Public Static Method:
public static function getInstance()
checks if an instance already exists. If not, it creates one and returns it.
Common Use Cases
- Database Connections: Ensuring only one connection is used throughout the application.
- Configuration Settings: Managing application-wide settings.
- Logging: Using a single logging instance to write logs.
Example: Database Connection Singleton
Here’s an example of a singleton for a database connection:
class Database {
private static $instance = null;
private $connection;
private function __construct() {
$this->connection = new PDO('mysql:host=localhost;dbname=test', 'root', '');
}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new Database();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
}
// Usage
$db = Database::getInstance();
$conn = $db->getConnection();
Example 2: Singleton datastore
Many times we need a data holder to hold some data for certain duration without directly persisting it in a database. In such case, a datastore helps to achieve the requirement.
This example shows how to use the Singleton pattern to hold data in a dataStore
array:
<?php
class DataStore {
private static $instance = null;
private $dataStore = [];
// Private constructor to prevent direct object creation
private function __construct() {}
// Method to get the single instance of the class
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new DataStore();
}
return self::$instance;
}
// Method to set data in the dataStore array
public function setData($key, $value) {
$this->dataStore[$key] = $value;
}
// Method to get data from the dataStore array
public function getData($key) {
return isset($this->dataStore[$key]) ? $this->dataStore[$key] : null;
}
// Method to get all data from the dataStore array
public function getAllData() {
return $this->dataStore;
}
}
// Usage example
$dataStore = DataStore::getInstance();
$dataStore->setData('name', 'John Doe');
$dataStore->setData('email', 'john.doe@example.com');
echo $dataStore->getData('name'); // Outputs: John Doe
echo $dataStore->getData('email'); // Outputs: john.doe@example.com
print_r($dataStore->getAllData()); // Outputs: Array ( [name] => John Doe [email] => john.doe@example.com )
?>
In this script:
- The
DataStore
class uses the Singleton pattern to ensure only one instance of the class exists. - The
setData
method allows you to store data in thedataStore
array. - The
getData
method retrieves data from thedataStore
array. - The
getAllData
method returns the entiredataStore
array.