Back to results for “Dependency injection”
PHP › Dependency Injection & Service Containers

What is the difference between singleton and transient bindings in a service container, and when should each be used?

Intermediate

Answer

A singleton binding, sometimes called shared, ensures the container returns the exact same instance of an object every time it is requested throughout the application's lifecycle, which is appropriate for objects like a database connection that should genuinely be shared, while a transient binding creates a brand new instance every single time it is requested, which is appropriate for lightweight, stateless objects where sharing a single instance offers no benefit and could even introduce unintended shared state bugs.
$container->singleton(DatabaseConnection::class, function () {
    return new DatabaseConnection(config('db'));
});
Real-world example An application binds its database connection as a singleton to avoid the overhead of establishing a brand new connection every single time any part of the code needs database access, while binding a lightweight report formatter as transient since each report genuinely needs its own fresh instance.

Common follow-ups: What happens if a singleton bound object accidentally accumulates unwanted state over the course of a request?;How do you decide whether a specific class should be bound as a singleton or transient?