Lesson 23 of 45 · Behavior and Variation
The Singleton Pattern
The "we only need one" instinct
There's a class in your codebase that should only have one instance. A configuration object. A logger. A connection to a third-party service. A cache. The instinct, especially for developers who learned design patterns from the Gang of Four book, is to reach for the Singleton Pattern: a class that enforces "only one of me will ever exist".
<?php
declare(strict_types=1);
namespace App\Payments;
use Stripe\StripeClient;
final class StripeGateway
{
private static ?self $instance = null;
private StripeClient $client;
private function __construct()
{
$this->client = new StripeClient(config('services.stripe.secret'));
}
private function __clone() {}
public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function client(): StripeClient
{
return $this->client;
}
}Anywhere in the code: StripeGateway::getInstance()->client()->paymentIntents->create([...]). The class itself enforces that only one instance ever exists. (services.stripe.secret is a key you add to config/services.php.)
This lesson is the one in this chapter that argues against the pattern it's named after. Singleton is included because it's a pattern developers reach for, and the uses I've seen are mostly better solved by something else. Knowing why is most of the value.
What the Singleton Pattern actually is
The Gang of Four definition:
Ensure a class only has one instance, and provide a global point of access to it.
Two things in one sentence: a uniqueness guarantee and a global access path. Both parts are problems.
The classical PHP shape (above) uses a private constructor, a private __clone() so clone can't make a second copy, a static instance property, and a public static accessor.
Why developers reach for it
Three reasons, all of them honest:
"It's expensive to create." Database connections, third-party clients, configuration loaders. Building one is real work; building it again at every call site is wasteful. Singleton prevents the duplication.
"There's only one logically." The application has one configuration. One logger destination. One cache backend. The "single" part of singleton matches the mental model.
"It's convenient."
Logger::getInstance()->info(...)is easy to write. No constructor parameter, no dependency injection, no setup. Just call it.
What goes wrong
Four specific problems show up wherever singletons live:
Hidden coupling. A class that calls Logger::getInstance() inside its methods is coupled to the logger globally. The constructor doesn't say so. The Dependency Injection vs Service Location lesson covered this: the singleton accessor hides the dependency the same way a call to the container does. Code that uses singletons is harder to read because the dependency graph is invisible.
Testability collapses. Tests want to swap dependencies for fakes. With DI, that's a constructor parameter. With singletons, it's mutating global state: Logger::setInstance($fake) if the class even allows it, and praying nothing else in the test process sees the change. Tests have to reset singletons between runs, deal with cross-test pollution, and mock at a global level.
Lifecycle problems. When does the singleton get built? When does it get torn down? In short-lived PHP requests, you often don't care. Under Octane (which runs on Swoole, RoadRunner or FrankenPHP), in queue workers, or in any other long-lived process, the singleton lives across requests or jobs, accumulating state, leaking memory, holding stale connections.
Concurrency hazards in long-running PHP. Under PHP-FPM, a worker process handles one request at a time, and PHP clears static properties when the request ends. A Swoole server with coroutines enabled, or an event loop such as ReactPHP or AMPHP, handles several requests at the same time in one process, and every request in flight sees the same static property. A singleton holding mutable state lets one request read what another request wrote, and the bug only shows up under concurrent load.
The Laravel "singleton" confusion
Laravel's container has a method called singleton(). Symfony has the same idea without the word: its services are shared by default. The provider below replaces StripeGateway with a binding for the Stripe API client, the one StripePayments from the Decorator Pattern lesson takes in its constructor:
<?php
declare(strict_types=1);
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Stripe\StripeClient;
final class StripeServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(StripeClient::class, function () {
return new StripeClient(config('services.stripe.secret'));
});
}
}This is not the Singleton Pattern. It's the container's lifetime policy: the container will hand out the same instance every time someone asks for StripeClient::class. The differences:
The class itself is a regular class. No private constructor, no
getInstance(), no global state.The "singleton-ness" is enforced by the container, not by the class.
Tests can override the binding. Different environments can bind different things.
It gives you the practical benefit of "only build it once" without the costs of the classical Singleton Pattern.
Laravel 13 also lets a class ask for this itself. The #[Singleton] attribute (Illuminate\Container\Attributes\Singleton) on a class tells the container to resolve it once, and #[Scoped] once per request or job. The class still has a public constructor and no static state, so a test can still put a fake in its place.
A singleton binding lives as long as the application instance. Under Octane or a queue worker, that instance outlives a single request or job. If an object must be rebuilt for each request or job, bind it with scoped() instead of singleton(): Laravel flushes scoped instances whenever a new request or job starts.
What to use instead
For almost every place where you'd reach for the classical Singleton Pattern, the answer is dependency injection with a single-instance binding:
The class is normal. Public constructor, regular dependencies, no static state.
Bind it in the container as a
singleton.Inject it into consumers through constructors.
Override the binding in tests with a fake.
You keep the "only one instance" benefit, and the dependency shows up in the constructor, where a test can replace it. Lifetime becomes a choice you make in the binding (singleton, scoped, or bind for a new instance each time), where a static property lives until the process ends.
When Singleton is genuinely defensible
The classical pattern is acceptable in a few cases:
The framework's own entry point. Laravel's container is a classic Singleton:
Container::getInstance()returnsstatic::$instance ??= new static, and theapp()helper calls it. Something has to hold the container where helper functions can reach it, before any injection is possible. That's framework code; your application code gets its dependencies through constructors instead.Pure-data constants. A registry of pre-computed lookup tables that genuinely never changes. I've seen this modeled as a singleton and as a class with all-static methods. Either is defensible because there's no state to mutate, no dependencies to test against.
Pitfalls
"Multiton" (the family of singletons). I've seen "we have one singleton per tenant" or "one per region". That's a singleton-keyed-by-something, with all the singleton problems multiplied by the number of keys, plus the new problem of key management. If you're tempted by this, you're describing a registry that should live in DI as a normal class with a lookup method.
The one thing to remember
If you're tempted to write a getInstance() method on a class, the right move is almost always to delete that thought, write a normal class, and bind it as a singleton in the container. You get one shared instance without inheriting the testability problems.
When you see a getInstance() in application code, treat it as a TODO: a piece of hidden coupling that wants to become a constructor parameter.
Related Links
- SingletonThe standard explanation of the classical Singleton pattern and its private constructor.
- Singleton in PHPA PHP example of a Singleton with getInstance(), the shape this lesson argues against.
- Binding A Singleton (Laravel Service Container)Laravel's singleton container binding, the container's lifetime policy this lesson distinguishes from the classical pattern.
- How to Define Non Shared Services (Symfony)Symfony's page on the shared option, which states that every service in the container is shared by default.
- Static Properties and Methods (PHP Manual)The PHP manual page on the static keyword, the mechanism behind a classical Singleton's getInstance().