Laravel Service Container, Properly: Bindings, Context and Decoration

11 min read

The service container is not an abstract pattern that Laravel happens to ship. It constructs controllers, queued jobs, listeners, commands, middleware and most framework integrations. That makes it easy to use accidentally: type-hint a concrete class and Laravel creates it. It also makes it easy to overuse: replace every new with app() and call the result “decoupled”.

The useful middle ground is simpler. Let Laravel autowire concrete, stateless classes. Add a binding only when the application must choose an implementation, control an object's lifetime, assemble a collection of plugins, or add a cross-cutting wrapper. This article builds an invoice-delivery boundary and uses it to explain those decisions without turning the container into a global variable.

Start with a concrete class, not a binding

After payment an order needs an invoice PDF. There is one renderer and no policy to select yet, so a concrete dependency says exactly what is true.

php
<?php

declare(strict_types=1);

namespace App\Billing;

use App\Models\Order;

final class InvoicePdfRenderer
{
    public function render(Order $order): string
    {
        return view('invoices.pdf', [
            'order' => $order,
        ])->render();
    }
}
php
<?php

declare(strict_types=1);

namespace App\Billing;

use App\Models\Order;

final class SendInvoiceAfterPayment
{
    public function __construct(
        private readonly InvoicePdfRenderer $renderer,
    ) {}

    public function handle(Order $order): void
    {
        $pdf = $this->renderer->render($order);

        MailInvoice::dispatch($order->getKey(), $pdf);
    }
}

Laravel reflects on SendInvoiceAfterPayment, sees InvoicePdfRenderer, and can build both classes. A provider binding would only repeat information the type system already supplies. The action remains testable: construct it with a lightweight real renderer, or introduce an interface later when a genuine variation appears.

An interface for every two-line class creates names without adding a decision. Bind abstractions at a boundary where the application has a reason to choose.

Introduce a contract at the delivery boundary

Email and a supplier portal are different delivery mechanisms. They fail differently, use different credentials, and should not be selected inside the renderer. That is a real seam.

php
<?php

declare(strict_types=1);

namespace App\Billing\Contracts;

use App\Models\Order;

interface InvoiceSender
{
    public function send(Order $order, string $pdf): void;
}
php
<?php

declare(strict_types=1);

namespace App\Billing;

use App\Billing\Contracts\InvoiceSender;
use App\Models\Order;
use Illuminate\Contracts\Mail\Mailer;

final class SesInvoiceSender implements InvoiceSender
{
    public function __construct(
        private readonly Mailer $mailer,
    ) {}

    public function send(Order $order, string $pdf): void
    {
        $this->mailer->to($order->billing_email)->send(
            new InvoiceMail(order: $order, pdf: $pdf),
        );
    }
}

The provider now records a deployment policy: the default sender is SES. The closure form is useful when construction needs configuration or a scalar parameter; mapping one class to another does not need it.

php
<?php

declare(strict_types=1);

namespace App\Providers;

use App\Billing\Contracts\InvoiceSender;
use App\Billing\SesInvoiceSender;
use Illuminate\Support\ServiceProvider;

final class BillingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(InvoiceSender::class, SesInvoiceSender::class);
    }
}

bind() resolves a new implementation each time the abstraction is requested. It is the safe default for stateless services. It does not promise to recursively rebuild every dependency; it says the container will not cache the resulting InvoiceSender as a shared instance.

Choose lifetime deliberately

The four commonly confused registrations answer different questions.

RegistrationMeaningAppropriate example
bind()Build on each resolutionStateless sender, formatter, action
singleton()One object for the worker/application lifetimeParsed immutable currency table, reusable SDK
scoped()One object per HTTP request or queue jobCorrelation and tenant context
instance()Share an already created objectA fake clock in a test, bootstrapped SDK

An immutable table is a defensible singleton: all state arrives through its constructor, never from the current user, request, tenant or job payload.

php
<?php

declare(strict_types=1);

namespace App\Billing;

final readonly class CurrencyTable
{
    /** @param array<string, int> $minorUnits */
    public function __construct(
        private array $minorUnits,
    ) {}

    public function minorUnitsFor(string $currency): int
    {
        return $this->minorUnits[$currency] ?? throw new \InvalidArgumentException(
            "Unsupported currency [{$currency}].",
        );
    }
}
php
<?php

declare(strict_types=1);

namespace App\Providers;

use App\Billing\CurrencyTable;
use Illuminate\Support\ServiceProvider;

final class CurrencyServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(CurrencyTable::class, function (): CurrencyTable {
            return new CurrencyTable(config('billing.currency_minor_units'));
        });
    }
}

Request state is the opposite. A singleton holding a tenant ID may appear fine under PHP-FPM because the process ends soon after the request. Under Octane, queue workers, or a long-running command it can disclose one request's state to the next. Use scoped(); Laravel flushes scoped objects for each new lifecycle.

php
<?php

declare(strict_types=1);

namespace App\Support;

final readonly class RequestContext
{
    public function __construct(
        public string $requestId,
        public ?int $tenantId,
    ) {}
}
php
<?php

declare(strict_types=1);

namespace App\Providers;

use App\Support\RequestContext;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\ServiceProvider;

final class RequestContextServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->scoped(RequestContext::class, function (): RequestContext {
            /** @var Request $request */
            $request = request();

            return new RequestContext(
                requestId: $request->header('X-Request-Id', Str::uuid()->toString()),
                tenantId: $request->user()?->tenant_id,
            );
        });
    }
}

The request helper belongs at this framework boundary, not in domain code. A domain action receives RequestContext explicitly, making its dependence on tenant identity visible to readers and tests.

Contextual binding answers a known-consumer question

The same application exports orders to CSV for accounting and produces a PDF for an account manager. Both classes depend on ReportFormatter, but the consumer determines the choice. This is exactly contextual binding.

php
<?php

declare(strict_types=1);

namespace App\Reports\Contracts;

use App\Models\Order;

interface ReportFormatter
{
    /** @param iterable<Order> $orders */
    public function format(iterable $orders): string;
}
php
<?php

declare(strict_types=1);

namespace App\Providers;

use App\Reports\Contracts\ReportFormatter;
use App\Reports\CsvReportFormatter;
use App\Reports\ExportOrders;
use App\Reports\PdfReportFormatter;
use App\Reports\PrintOrderReport;
use Illuminate\Support\ServiceProvider;

final class ReportingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->when(ExportOrders::class)
            ->needs(ReportFormatter::class)
            ->give(CsvReportFormatter::class);

        $this->app->when(PrintOrderReport::class)
            ->needs(ReportFormatter::class)
            ->give(PdfReportFormatter::class);
    }
}

Contextual binding does not select a formatter from a request parameter, database row, or customer plan. At resolution time the container knows which class it is building, not which business policy should apply. Put runtime choice in an explicit resolver.

php
<?php

declare(strict_types=1);

namespace App\Reports;

use App\Reports\Contracts\ReportFormatter;
use Illuminate\Contracts\Container\Container;

final class ReportFormatterResolver
{
    /** @param array<string, class-string<ReportFormatter>> $formatters */
    public function __construct(
        private readonly Container $container,
        private readonly array $formatters,
    ) {}

    public function forFormat(string $format): ReportFormatter
    {
        $formatter = $this->formatters[$format] ?? throw new \InvalidArgumentException(
            "Unsupported report format [{$format}].",
        );

        return $this->container->make($formatter);
    }
}

This use of the container is appropriate because a resolver is a composition boundary translating runtime configuration into a concrete service. A controller calls forFormat(), not app() itself.

Tags collect extensions; they do not replace order

An order may need several independent checks before its invoice is sent. Each check is a plugin and the application wants all of them. A tag makes that collection declarative.

php
<?php

declare(strict_types=1);

namespace App\Billing\Contracts;

use App\Models\Order;

interface InvoiceGuard
{
    public function assertCanSend(Order $order): void;
}
php
<?php

declare(strict_types=1);

namespace App\Providers;

use App\Billing\EnsureOrderIsPaid;
use App\Billing\EnsureRecipientHasEmail;
use Illuminate\Support\ServiceProvider;

final class InvoiceGuardServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->tag([
            EnsureOrderIsPaid::class,
            EnsureRecipientHasEmail::class,
        ], 'invoice.guards');
    }
}
php
<?php

declare(strict_types=1);

namespace App\Billing;

use App\Billing\Contracts\InvoiceGuard;
use App\Models\Order;
use Illuminate\Contracts\Container\Container;

final class InvoiceGuardPipeline
{
    public function __construct(
        private readonly Container $container,
    ) {}

    public function assertCanSend(Order $order): void
    {
        foreach ($this->container->tagged('invoice.guards') as $guard) {
            if (! $guard instanceof InvoiceGuard) {
                throw new \LogicException('The invoice.guards tag contains an invalid service.');
            }

            $guard->assertCanSend($order);
        }
    }
}

Tags work for independently added extensions. If check order is business meaningful, make it explicit: give guards a priority contract and sort them, or write a pipeline whose sequence is visible in one place. Do not allow registration order to quietly become business policy.

Decorate a boundary with extend()

Logging successful delivery is not an invoice sender's primary job. A decorator wraps the resolved sender without teaching every sender about observability.

php
<?php

declare(strict_types=1);

namespace App\Billing;

use App\Billing\Contracts\InvoiceSender;
use App\Models\Order;
use Psr\Log\LoggerInterface;

final class LoggedInvoiceSender implements InvoiceSender
{
    public function __construct(
        private readonly InvoiceSender $inner,
        private readonly LoggerInterface $logger,
    ) {}

    public function send(Order $order, string $pdf): void
    {
        $this->inner->send($order, $pdf);

        $this->logger->info('Invoice sent.', [
            'order_id' => $order->getKey(),
        ]);
    }
}
php
<?php

declare(strict_types=1);

namespace App\Providers;

use App\Billing\Contracts\InvoiceSender;
use App\Billing\LoggedInvoiceSender;
use Illuminate\Contracts\Container\Container;
use Illuminate\Support\ServiceProvider;
use Psr\Log\LoggerInterface;

final class InvoiceObservabilityServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->extend(InvoiceSender::class, function (
            InvoiceSender $sender,
            Container $container,
        ): InvoiceSender {
            return new LoggedInvoiceSender(
                inner: $sender,
                logger: $container->make(LoggerInterface::class),
            );
        });
    }
}

Register the original binding before extending it. Decide where retries belong: usually the queued job or HTTP-client configuration, not an invisible decorator that changes delivery semantics for every caller.

make, makeWith, call, and app() have narrow roles

Constructor injection is the default because it documents dependencies. Use make() at composition edges such as a factory or runtime resolver. Use makeWith() when an otherwise resolvable class needs a scalar selected there.

php
<?php

declare(strict_types=1);

namespace App\Exports;

use Illuminate\Contracts\Container\Container;

final class ExportFactory
{
    public function __construct(
        private readonly Container $container,
    ) {}

    public function forPath(string $path): OrderExport
    {
        return $this->container->makeWith(OrderExport::class, [
            'destinationPath' => $path,
        ]);
    }
}

call() suits framework-managed callbacks and command-style methods whose collaborators Laravel can inject. It is not a reason to move a class's stable dependencies from its constructor into a method. resolve() and app()->make() use the same container; neither name makes hidden dependencies better. In a provider, factory, command bootstrap or resolver they are normal. In a controller, listener or domain service they are usually a design smell.

Circular dependencies are a design result

When Laravel reports A -> B -> A, do not inject the container into one side to postpone the failure. The cycle says both services claim the same operation. If InvoiceSender asks OrderService to mark an invoice sent while OrderService asks InvoiceSender to send it, two classes own one workflow. Introduce a SendInvoice action to orchestrate both, or extract a smaller InvoiceDeliveryStatus contract. The container did not create the coupling; it made it visible.

When not to use the container this way

Do not bind a stable concrete class merely to satisfy a diagram. Do not use contextual binding when a plan, feature flag or request chooses an implementation; that is runtime policy and needs a resolver. Do not put request data in a singleton, especially under Octane or queue workers. Do not use tags for a fixed three-step workflow where a direct constructor list is easier to read. And do not use extend() merely to avoid changing code you own: a direct dependency can be clearer than a hidden decoration stack.

The alternative is not “no architecture”; it is explicit composition. A small factory, a match for two stable runtime options, or a constructor with two dependencies is often more honest than an early abstraction. The container earns its place when it records a real application choice.

Production pitfalls to review

The most expensive container bugs tend to be lifecycle and visibility bugs:

  • A singleton captures Request, Auth, tenant, locale or mutable collection state, then leaks it in a long-lived worker.
  • A provider resolves a service while registering bindings, freezing an old implementation before another provider can extend it.
  • A tag is trusted without validating its members, so a bad registration fails far from its source.
  • A decorator changes retries, transactions or exception handling without its callers knowing their contract changed.
  • Generic app() calls spread through business code, forcing tests to boot the whole framework just to construct one action.

For each binding, ask four questions in review: what decision is it encoding, who owns it, how long may the instance live, and can a test provide the collaborator directly? With clear answers, the container stays a small composition tool rather than the application's hidden control flow.

Related articles

Existing system support

Need help with a live application?

I help companies improve live systems, clean up delivery workflows, and ship new features without adding avoidable complexity.

Comments (0)
Sign in to leave a comment

You need to be signed in to add a comment.

Login

Need someone to take responsibility for the next step?

Let’s talk about your project and define a scope that actually makes sense for your goals.