Author - StudySection Post Views - 143 views
Singleton

Singleton pattern in PHP

In the Singleton Design Pattern, we guarantee that there is only one instance of a class and that it is globally accessible. The Singleton design pattern restricts classes to a single object.

How to use it?

We need to create a Singleton class:

  1. static member variable: This acts as a placeholder for an instance of the class.
  2. Private constructor: A private constructor prevents a class from being instantiated directly.
  3. Prevent objects from being cloned by modifying the clone wizard.
  4. Create a static method for global access.

<?php
class Singleton {
private static $_instance = null;
/* Prevent direct instantiation of a class. */
private function __construct() {}
/* Prevent object cloning. */
private function __clone() {}
/* Static method to provide global access point. */
public static function getInstance()
{
if(self::$_instance == null) {
self::$_instance = new Singleton();
}
return self::$_instance;
}
/* Prevent unserializing of singleton instance */
private function __wakeup() {}
}
$obj1 = Singleton::getInstance();
$obj2 = Singleton::getInstance();
var_dump($obj1);
var_dump($obj2);
?>

In this example, I created two variables that represent the same object. The first time the getInstance() method is called, it will create a new object. Any call after that will just return the design object.
Create a simple database connection class using the Singleton Design pattern.

<?php
class DatabaseConnection {
private $_connection;
private static $_instance;
private $_dbhost = "localhost"
private $_dbusername = "root";
private $_dbpassword = "123456";
private $_dbdatabase = "ams_dev";
private function __construct() {
$this->_connection = new mysqli($this->_dbhost, $this->_dbusername,
$this->_dbpassword, $this->_dbdatabase);
if(mysqli_connect_error()) {
trigger_error("Connection Failed" . mysqli_connect_error(),
E_USER_ERROR);
}}
public static function getInstance() {
if(self::$_instance == null) {
self::$_instance = new self();
}
return self::$_instance;
}
private function __clone(){}
public function getConnection(){
return $this->_connection;
}}

This design pattern is very useful when we require one instance of a class for the entire lifecycle of a request in a web application. Apply this design pattern to your logger class, configuration class, etc., where only one global entry point is needed.

Being the most extensively used JavaScript library, a jQuery Certification will add enormous value to your skill-set. jQuery provides various functionalities to the developer in order to develop complex applications with ease and efficiency.

Leave a Reply

Your email address will not be published. Required fields are marked *

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri