Singleton Pattern
What Is It?
The Singleton Pattern ensures a class has only one instance and provides a global point of access to it. In Laravel, the service container manages singletons.
Why?
Some resources should only exist once: database connections, configuration managers, cache connections. Creating multiple instances wastes resources and causes inconsistencies.
When to Use
For shared resources: database connections, configuration, cache, logging, session management. Laravel uses singletons for many built-in services.
When Not to Use
For classes that maintain per-request state. For classes that need to be tested in isolation (singletons are harder to mock). For classes that should have multiple instances.
Example
Example
<?php
// Service Provider singleton registration
public function register(): void
{
$this->app->singleton(CacheManager::class, function ($app) {
return new CacheManager($app);
});
// Always returns the same instance
$cache1 = app(CacheManager::class);
$cache2 = app(CacheManager::class);
// $cache1 === $cache2 is true
}
// Custom singleton
class DatabaseConnection
{
private static ?self $instance = null;
private function __construct(private array $config) {}
public static function getInstance(array $config = []): self
{
if (self::$instance === null) {
self::$instance = new self($config);
}
return self::$instance;
}
}
// Laravel\'s built-in singletons
// Config, Cache, Event, Log, Queue are all singletons
\Illuminate\Support\Facades\Cache::singleton('cache.store', function ($app) {
return $app['cache']->store();
});
Pros
- Ensures single instance
- Global access point
- Lazy initialization
- Reduces memory usage
- Laravel container manages lifecycle
Cons
- Harder to test (can't inject mock easily)
- Tight coupling to global state
- Violates Single Responsibility Principle
- Can mask design problems
- Difficult to extend or subclass