07
July 2021
The singleton pattern in PHP
We use the singleton pattern in order to restrict the number of instances that can be created from a resource consuming class to only one.
Resource consuming classes are classes that might slow down our website or cost money. For example:
- Some external service providers (APIs) charge money per each use.
- Some classes that detect mobile devices might slow down our website.
- Establishing a connection with a database is time consuming and slows down our app.
So, in all of these cases, it is a good idea to restrict the number of objects that we create from the expensive class to only one.
Use a singleton pattern to restrict the number of objects to only one!
The anatomy of a singleton pattern
Let's start by understanding the structural characteristics of a class that obeys the singleton pattern:
- A private constructor is used to prevent the direct creation of objects from the class.
- The expensive process is performed within the private constructor.
- The only way to create an instance from the class is by using a static method that creates the object only if it wasn't already created.
Why is it a singleton?
Since we restrict the number of objects that can be created from a class to only one, we end up with all the variables pointing to the same, single object.
Practical example::database class
Let's demonstrate the singleton pattern with a class that establishes a database connection, and restricts the number of instances to only one.
Since we use a class that checks if a connection already exists before it establishes a new one, it really doesn't matter how many times we create a new object out of the class, we still get the same connection. To prove the point, let's create three instances out of the class and var dump them.
The result is the same connection for the three instances.
Class that doesn't use a singleton to contact the database
To understand the problem that the singleton pattern solves, let's consider the following class that has no mechanism to check if a connection already exists before it establishes a new connection.
Now, each time we create a new object, we also establish a new database connection.
This has implications for slowing down the system because each new connection with the database costs time.
The singleton pattern::the good, the bad, and the ugly
The singleton pattern is probably the most infamous pattern to exist, and is considered an anti-pattern because it creates global variables that can be accessed and changed from anywhere in the code.
Yet, The use of the singleton pattern is justified in those cases where we want to restrict the number of instances that we create from a class in order to save the system resources. Such cases include data base connections as well as external APIs that devour our system resources.
Source: https://phpenthusiast.com