Understanding Singleton Pattern
What is singleton?
Singleton is the type of creational design pattern used to contribute for the best practices in software development. The main purpose of this pattern is to share single point of access, anywhere within the application , ensuring the single instance of class. The process of object creation, setup and getting instance is encapsulated with this pattern.
Characteristics of Singleton
Single instance - resolves class to produce on instance discouraging the usage of resource for multiple instance creation
Global Accessibility - The instance of class is accessible anywhere from the system.
Lazy Loading - We don't need to worry about getting instance of class, as singleton creates instance when it is called for the first time.
Noticeable usage within Laravel
The singleton pattern is being used in along with different feature and packages provided by Laravel.
Service container:- Service container is powerful tool in Laravel for dependency management and injection. Here singleton pattern is use to return single instance of bound class on several requests.
Database Connection:- Database manager uses singleton to ensure efficient connection with single instance delivery when needed.
Configuration Management:- configuration management uses singleton pattern to load configuration value initially and provide the cached values on request.
Logging System:- Laravel's logging system uses singleton to share the single logger instance ensuring the same logging pattern across the system.
Cache System:- Caching system of Laravel uses singleton to resolve the single instance of cache stores, optimizing the performance without the need for multiple re-initialization.
Event Dispatcher:- Uses singleton to share single instance of dispatcher allowing registration of components and listen to it globally with event.
File System:- Singleton is used by file system manager to facilitates the interaction with different types of file systems with single instance of Laravel's file system.
Simple Php Implementation
Here is the example of simple singleton implementation:
<?php
class SimpleSingleton
{
// Assign the class instance.
private static $instance = null;
private static $firstCall = false;
//private constructor to prevent instantiation
//from outside this class
private function __construct() {}
//set instance on first call to $instance
//and return it from next request
public static function getInstance()
{
self::$firstCall = self::$instance === null;
self::$instance = self::$instance ?? new self();
return self::$instance;
}
// Chainig this method after getting
//instance should return the message accordingly
public function showMessage()
{
echo self::$firstCall
?
"Hi! its first time and you will get the new instance"
:
"You will be having instance same as previous";
}
}
// Usage example:
$firstInstance = SimpleSingleton::getInstance();
echo $firstInstance->showMessage();// Hi! its first time and you will get the new instance
// on attempt to crete new instance, will return the same instance.
$secondInstance = SimpleSingleton::getInstance();
echo $firstInstance->showMessage();// You will be having instance same as previous"
echo($firstInstance === $secondInstance); // true
Simple usage with Laravel
With app() helper function and singleton method on service container ,we can easily bind class or callback function, that will be resolved only once. Same instance is received on subsequent calls across the system.
<?php
app()->singleton(
'simpleSingleton',
fn()=>SimpleSingleton::getInstance()
);
$thirdInstance = app('simpleSingleton');
echo $thirdInstance->showMessage();
References
Conclusion
To conclude, singleton pattern plays a significant role on resource utilisation ensuring the single point of access globally. Laravel framework has underscored the significant performance optimization and adhered the creational design pattern with the implementation of singleton to its core features like the Service Container, Database Connection, Configuration Management, Logging System, Cache System, Event Dispatcher, and File System.
I have tried to support my opinion on singleton with example including the basic usage with php and using available methods in Laravel for instant singleton binding and access.
I hope this information was helpful ๐. Please feel free to ask me any other questions you may have. I am always happy to help ๐ค.
Subscribe to my newsletter
Read articles from manish maharjan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by