๐Ÿš€ Day 1 : Laravel Service Container : bind() vs singleton() vs scoped()

Laravel Service Container

Most Laravel developers know dependency injection.

Far fewer understand how Laravel decides which object instance to create, when to reuse it, and when to create a new one.

That distinction becomes critical in long-running workers, queues, Octane, tests, and large applications.

Let's go under the hood. ๐Ÿ‘‡


๐Ÿง  First: What problem does the Service Container solve?

Consider:

class OrderController
{
    public function __construct(
        private PaymentService $paymentService
    ) {}
}

Laravel needs to answer:

"How do I create PaymentService?"

The Service Container is responsible for resolving that dependency.

At a high level:

Controller ↓ Container ↓ PaymentService ↓ PaymentRepository ↓ Database Connection

The container builds the dependency graph for you.

But the interesting part is object lifetime.


๐Ÿ”ฅ bind() — Create a new instance when resolved

Example:

$this->app->bind(
    PaymentService::class,
    fn ($app) => new PaymentService(
        $app->make(PaymentRepository::class)
    )
);

Conceptually:

resolve() ↓ Create instance ↓ resolve() again ↓ Create another instance

So:

$a = app(PaymentService::class); $b = app(PaymentService::class);

Generally:

$a !== $b

This is useful when you don't want shared state between resolutions.


⚡ singleton() — One instance for the container lifecycle

Now:

$this->app->singleton( PaymentService::class, fn ($app) => new PaymentService( $app->make(PaymentRepository::class) ) );

The first resolution creates the object.

Later resolutions reuse it:

First resolve ↓ Create object ↓ Store object ↓ Second resolve ↓ Return existing object

Therefore:

$a = app(PaymentService::class); $b = app(PaymentService::class);

Typically:

$a === $b

This can be useful for genuinely shared, stateless infrastructure.

But there's an important warning.


๐Ÿšจ Singleton can become dangerous when state is stored

Imagine:

class UserContext { public ?int $userId = null; }

And registering:

$this->app->singleton(UserContext::class);

If the object stores request-specific information, you can create a lifecycle problem.

Why?

Because a singleton can live longer than you expect depending on the execution environment.

This becomes especially important with:

  • Laravel Octane

  • queue workers

  • long-running processes

  • persistent application servers

A singleton containing request-specific state is a potential architectural bug.


๐Ÿ†• scoped() — The important middle ground

Laravel provides:

$this->app->scoped( UserContext::class, fn () => new UserContext() );

A scoped binding is reused within a particular application lifecycle/scope, then recreated when the scope is flushed.

Conceptually:

Request #1 ↓ UserContext A ↓ Request ends ↓ Scope reset Request #2 ↓ UserContext B

This is particularly important for applications running in environments where the framework process stays alive.


๐Ÿงจ Why Laravel Octane changes the game

Traditional PHP applications commonly work like:

Request ↓ PHP execution ↓ Response ↓ Process ends

With long-running application servers:

Start worker ↓ Application stays in memory ↓ Request 1 ↓ Request 2 ↓ Request 3 ↓ Request 4 ↓ ...

Now your application's object lifecycle matters much more.

A poorly designed singleton can accidentally retain state across requests.

That can lead to extremely difficult bugs.


๐Ÿ”ฌ Think about object lifetime, not just dependency injection

When registering a service, ask:

1. Should every resolution create a new object?

Use:

bind()

2. Should the same object be reused?

Consider:

singleton()

3. Should it be reused only inside a particular application/request scope?

Consider:

scoped()

The correct choice depends on the state and lifecycle of the object.


๐Ÿงฉ Contextual Binding — Where things get really interesting

Suppose two services require the same interface:

interface PaymentGateway { public function charge(); }

But:

OrderService → StripeGateway SubscriptionService → RazorpayGateway

Instead of manually constructing everything, Laravel can use contextual bindings.

Conceptually:

$this->app ->when(OrderService::class) ->needs(PaymentGateway::class) ->give(StripeGateway::class);

And:

$this->app ->when(SubscriptionService::class) ->needs(PaymentGateway::class) ->give(RazorpayGateway::class);

Now the container isn't simply asking:

"What implementation does this interface have?"

It's asking:

"What implementation does this consumer need?"

That's powerful for large applications.


๐Ÿ—️ A useful architecture pattern

Instead of putting everything directly inside controllers:

Controller ↓ Business Service ↓ Interface ↓ Infrastructure Implementation

For example:

OrderController ↓ OrderService ↓ PaymentGateway ↓ StripeGateway

Your business logic doesn't need to know the concrete payment provider.

This makes systems easier to:

  • test

  • replace

  • extend

  • maintain

  • integrate


๐Ÿšจ Common production mistake

Don't register everything as a singleton just because:

"It improves performance."

That's not a safe assumption.

The important question is:

Does this object contain mutable state?

If yes, you need to carefully consider its lifecycle.

For example, be cautious with objects containing:

$user $request $tenant $currentAccount $currentLocale $currentPermissions

when registering them with a long-lived lifetime.


๐Ÿง  The advanced mental model

Don't think:

Service Container = Dependency Injection

Think:

Service Container ↓ Dependency Graph + Binding Rules + Object Lifetime + Contextual Resolution + Lifecycle Management

That's the level at which the container becomes an architectural tool, not just a Laravel convenience.


๐Ÿ”ฅ The question senior Laravel developers should ask

Before writing:

$this->app->singleton(...)

don't ask:

"Can I make this a singleton?"

Ask:

"What state does this object hold, and how long should that state live?"

That single question can prevent some very subtle bugs.


Day 1/25 complete.

Tomorrow we'll go deeper into:

๐Ÿ‘‰ Laravel Service Providers & Application Bootstrapping — what actually happens during register() vs boot(), why provider order matters, and how Laravel assembles the application before your request reaches the controller.


Comments

Popular Posts

How to setup phpstorm in windows for laravel

๐Ÿš€ Day 5 : Advanced Laravel : Eloquent ORM — What REALLY Happens When Database Rows Become PHP Objects?

๐Ÿš€ Day 4 : Advanced Laravel Internals : Middleware Pipeline — What Happens Before AND After Your Controller?