Pius Adams Ijachi
2 min readJan 11, 2024

Singleton Design Pattern

The singleton pattern is a design pattern that ensures that only one instance of a class exists in the application. It also provides a global access point to that instance. The singleton pattern is useful when controlling access to a shared resource, such as a database connection, a configuration file, or a logger.

However, the singleton pattern also has some drawbacks. It can introduce tight coupling between classes, making them harder to test and maintain. It can also hide the dependencies of your code, making it less clear what your classes need to function properly. And it can violate the single responsibility principle, as the singleton class may have more than one reason to change.

Therefore, I don’t totally recommend using the singleton pattern unless you really need it. A better alternative is to use dependency injection, which allows you to pass the dependencies of your classes as parameters, rather than accessing them globally. This way, you can have more control over the creation and lifetime of your objects, and you can easily mock them for testing purposes.

For example, instead of using the LoggingSingleton class directly in your code, you could create an interface for logging, and then implement different logging strategies that conform to that interface. Then, you could inject the logging strategy that you want to use into your classes that need logging functionality. This would make your code more flexible and testable, and you could switch between different logging strategies without changing your code.

<?php
namespace Singleton;class LoggingSingleton
{
private static ?LoggingSingleton $instance = null; private function __construct()
{
}
public static function getInstance(): LoggingSingleton
{
if (self::$instance == null) {
self::$instance = new LoggingSingleton();
}
return self::$instance;
}
public function log($message): void
{
echo $message;
}
}
// usage
<?php
use Singleton\LoggingSingleton;require_once "LoggingSingleton.php";$log = LoggingSingleton::getInstance();$log->log('Hello world');

Below is the link to GitHub and a design pattern video

git

https://www.youtube.com/watch?v=hUE_j6q0LTQ