Backend Development

Singleton Patten In PHP With Real World Example

Today we will explore one of the php design patterns that is commonly used in most frameworks and languages which is the Singleton Pattern.

 

Ensures that class has only one instance, and provides a global point of access of it.

 

The key point in this pattern is that you define a class with private constructor and public static function that returns instance from the class every time we use it. the private constructor here will disable the default instantiation of the class using new keyword.

As a real world example of it we will create a database class that has global variable and all classes have access to it.

<?php
class DatabaseManager{

    private static $instance;

    /**
    * private constructor

    */ 
    private function __construct()
    {
        // here for example you make a connection to a databse
    }

    /**
     * getInstance
     * 
     * this method will return instance of the class
     */
    public static function getInstance(){
        if(!self::$instance)
            self::$instance = new self;

        return self::$instance;
    }

    public function query($statement) 
    {
       // query the database
    }
}

 

In the class above we created a static method getInstance to return instance of the class if it exists or create a new one if it doesn’t exist.

 

To use it

<?php
$db = DatabaseManager::getInstance();

$db->query();

 

Note that if try to create a new instance using the new keyword a Fatal error will appear like that:

Fatal error: Uncaught Error: Call to private DatabaseManager::__construct()

and this happens because of the private constructor



So what is the difference between creating instance using the new keyword and when you use singleton pattern?

To illustrate this lets make the constructor as public and print the object with var_dump():

<?php
class DatabaseManager{

    private static $instance;

    /**
    * public constructor

    */ 
    public function __construct()
    {
        // here for example you make a connection to a databse
    }

    /**
     * getInstance
     * 
     * this method will return instance of the class
     */
    public static function getInstance(){
        if(!self::$instance)
            self::$instance = new self;

        return self::$instance;
    }

    public function query($statement) 
    {
       // query the database
    }
}

$db1 = new DatabaseManager();
$db2 = new DatabaseManager();
$db3 = new DatabaseManager();

// print these objects
echo "<pre>";
var_dump($db1, $db2, $db3);
echo "</pre>";

When you run the above script it will show a new identifier for the class #1, #2, #3 which means the three objects are totally separate:

object(Database)#1 (0) {
}
object(Database)#2 (0) {
}
object(Database)#3 (0) {
}

 

But with singleton pattern method only one identifier #1 is created like this:

object(Database)#1 (0) {
}
object(Database)#1 (0) {
}
object(Database)#1 (0) {
}

As shown above you now understand the power of the singleton pattern, how its created and why it should be used in scenarios like that.

0 0 vote
Article Rating

What's your reaction?

Excited
0
Happy
0
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mohammed elkady
Mohammed elkady
2 years ago

Great article. Keep it up

engineer-florence
engineer-florence
1 year ago

now this makes more sense, thank you!