Skip to content

Lesson 13 of 45 · Wiring Things Together

Dependency Injection vs the Service Locator Pattern

Intermediate•
lesson•
October 19, 2026•
~12 min read

Two ways to get a hold of something

A class needs a Mailer to do its job. There are two common ways it gets one in PHP:

PHP
<?php // Option A: ask for it declare(strict_types=1); namespace App\Reservations; use App\Booking\Guest; use App\Reservations\Mail\ReservationConfirmedEmail; use Illuminate\Contracts\Mail\Mailer; final class SendReservationConfirmation { public function send(Guest $guest, Reservation $reservation): void { $mailer = app(Mailer::class); // service location $mailer->to($guest->email()->value)->send(new ReservationConfirmedEmail($reservation->id)); // The facade version is the same lookup in one line: // Mail::to($guest->email()->value)->send(new ReservationConfirmedEmail($reservation->id)); } }
PHP
<?php // Option B: receive it declare(strict_types=1); namespace App\Reservations; use App\Booking\Guest; use App\Reservations\Mail\ReservationConfirmedEmail; use Illuminate\Contracts\Mail\Mailer; final readonly class SendReservationConfirmation { public function __construct( private Mailer $mailer, // dependency injection ) {} public function send(Guest $guest, Reservation $reservation): void { $this->mailer->to($guest->email()->value)->send(new ReservationConfirmedEmail($reservation->id)); } }

Both work, and the difference is a few lines.

This lesson is about why option B is the default this course argues for, why option A is so common in PHP anyway, and where each one earns its place.

What dependency injection is

Dependency injection is the practice of giving a class its dependencies from outside (usually through the constructor) instead of letting the class fetch them itself.

The dependencies are injected into the class. The class doesn't know whether they came from a container, a factory, a test, or a hand-written new. It just receives them and uses them.

The signature of the class becomes the contract: "I need these things to do my job". The constructor is the document of that contract. Anyone reading the class can see what it depends on, and anyone changing it can see what to change.

What service location is

Service location is the practice of asking a global registry (a "service locator") for the dependencies you need, when you need them.

In Laravel, this looks like app(SomeService::class). It also looks like facades (Mail::send(...), Cache::get(...), DB::table(...)). It also looks like global helpers (auth(), request(), now()). All of these reach into a container or global state to get something the class needs.

Laravel makes service location the path of least resistance. You don't have to declare the dependency, wire the container, or update the constructor. You just call the helper.

Why DI wins

Three concrete things DI gives you that service location doesn't:

  • Honest dependencies. The constructor signature lists what the class needs. With service location, the dependencies are buried inside method bodies. To find what a service-located class needs, you have to search every method, closure, and branch for app(...) calls, facades, and helpers.

  • Tests that don't need the container. Both styles can be stubbed. Martin Fowler's article Inversion of Control Containers and the Dependency Injection pattern makes the same point: "both are very amenable to stubbing". The difference is where the fake goes. With DI, the test passes it to the constructor and the class under test never touches the container. With service location, the test has to bind the fake into the container before the code runs, so the test has to set up the container first.

  • No hidden coupling. A class with app(Mailer::class) inside is coupled to the global container's idea of what Mailer is right now. That can change between tests and between environments. A class with Mailer $mailer in the constructor is coupled to whatever was passed in, and that's it. The reasoning is local.

This is framework coupling versus framework decoupling at a smaller scale. Service location is framework coupling sneaking into individual classes. DI is the local fix.

Why service location is so common in PHP

If DI is so much better, why do so many of the PHP codebases I've worked on have facades and app() calls everywhere?

Three reasons, none of them malicious:

  • Frameworks make it easy. Laravel's facades and global helpers are the friendly path. Tutorials show them because tutorials optimize for getting a first example working, and they don't show what the same code looks like once the codebase has grown.

  • It looks shorter. Mail::send(...) is one line. The DI version needs a constructor parameter and $this->mailer in the method. That's a few lines, written once per class, but at the moment of typing one method it feels like more setup.

  • The container's there anyway. Once Laravel boots, the container is sitting in memory. Reaching into it from anywhere doesn't feel expensive.

Where service location is genuinely fine

To stay honest with the "tools, not rules" framing, service location isn't always the wrong call:

  • Small scripts and one-off jobs. Throwaway Artisan commands, one-off tooling, glue code at the boundaries. The cost of explicit DI doesn't pay off for code that few people will ever read.

  • Framework integration points. Some places (route files, service providers and the container bindings inside them) genuinely have to touch the container. That's their job. Helpers like route(), redirect() and view() belong at the same edges, and test helpers like Mail::fake() are fine as test scaffolding.

  • Truly global concerns. A logger, in some codebases, is treated as ambient. A deliberate global like Log::info(...) can be defensible when the alternative (injecting a logger into every single class) is more friction than it's worth. The trade is real and a judgment call.

Symfony draws the line in its own documentation. Every service is "private by default", and "When a service is private, you cannot access it directly from the container using $container->get(); the only way to use it is dependency injection." For a class that has to fetch services at runtime, Symfony offers a service locator instead: a small container that holds a declared list of services and "only instantiates each of them when it's actually used". This is still service location, but the scope makes it fine: the class names every service it can fetch, and asking for anything else throws. Symfony's own AbstractController works this way. Its render() and generateUrl() methods fetch Twig and the router from a locator built from the services its getSubscribedServices() method lists, not from the whole container. The Strategy Pattern lesson uses a locator to pick a cancellation policy by key.

The general principle: in business code, default to DI. At framework boundaries, service location is sometimes the practical choice.

Constructor injection in PHP

The default style in modern PHP, and the one this course uses everywhere, is constructor injection with promoted, readonly properties:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Framework\Events\EventDispatcher; use App\Payments\Payments; use Psr\Clock\ClockInterface as Clock; final readonly class CancelReservationCommandHandler { public function __construct( private Reservations $reservations, private Payments $payments, private EventDispatcher $events, private Clock $clock, ) {} public function handle(CancelReservationCommand $command): void { /* ... */ } }

This is the handler from the Anemic Domain Model vs Rich Domain Model lesson with one change: it depends on EventDispatcher, a small interface this course owns, instead of Laravel's Dispatcher. Laravel's contract has nine methods, and a test spy would have to implement all of them. The method body is the same as in that lesson, so it is elided here. The container resolves the four constructor dependencies by type when it builds the handler (more on that below). Here is the interface, the production adapter, and the spy:

PHP
<?php declare(strict_types=1); namespace App\Framework\Events; interface EventDispatcher { public function dispatch(object $event): void; }
PHP
<?php declare(strict_types=1); namespace App\Framework\Events; use Illuminate\Contracts\Events\Dispatcher; final readonly class LaravelEventDispatcher implements EventDispatcher { public function __construct(private Dispatcher $dispatcher) {} public function dispatch(object $event): void { $this->dispatcher->dispatch($event); } }
PHP
<?php declare(strict_types=1); namespace App\Testing; use App\Framework\Events\EventDispatcher; final class RecordingDispatcher implements EventDispatcher { /** @var list<object> */ public array $dispatched = []; public function dispatch(object $event): void { $this->dispatched[] = $event; } }

Tests can pass fakes (FakePayments is a hand-written implementation of the Payments interface from the Decorator Pattern lesson, and InMemoryReservations implements Reservations with an array; both are shown in the Test Doubles lesson):

PHP
<?php declare(strict_types=1); namespace App\Reservations\Tests; use App\Reservations\CancelReservationCommand; use App\Reservations\CancelReservationCommandHandler; use App\Reservations\Exceptions\ReservationNotFound; use App\Reservations\ReservationId; use App\Testing\FakePayments; use App\Testing\FrozenClock; use App\Testing\InMemoryReservations; use App\Testing\RecordingDispatcher; use PHPUnit\Framework\TestCase; final class CancelReservationCommandHandlerTest extends TestCase { public function test_cancelling_an_unknown_reservation_throws(): void { $handler = new CancelReservationCommandHandler( reservations: new InMemoryReservations(), payments: new FakePayments(), events: new RecordingDispatcher(), clock: new FrozenClock('2026-05-09'), ); $this->expectException(ReservationNotFound::class); $handler->handle(new CancelReservationCommand(ReservationId::next(), 'Guest asked to cancel')); } }

The test needs no container, so it is fast and isolated.

Injecting time

Business code that calls new DateTimeImmutable() or the now() helper directly is reaching for a hidden dependency, in exactly the sense the rest of this lesson describes. The call isn't visible in the constructor. A test that exercises date logic gets whatever the wall clock says when it runs, and some bugs only appear at specific moments: a "days until check-in" calculation that passes all week and fails right at midnight, or an "is this reservation within the month" check that's fine until a test runs on the 1st.

Laravel can freeze now() in a test with $this->travelTo(), and it resets the frozen time after each test. That freeze is global state, and it only works in a test that boots the framework. It never reaches new DateTimeImmutable(), and the class still doesn't say that it depends on time.

The fix is the same one this lesson applies everywhere else: receive the time, don't reach for it. PSR-20 defines the standard shape for this, Psr\Clock\ClockInterface, with one method, now(): DateTimeImmutable. A production implementation reads the real clock:

PHP
<?php declare(strict_types=1); namespace App\Support; use DateTimeImmutable; use Psr\Clock\ClockInterface; final class SystemClock implements ClockInterface { public function now(): DateTimeImmutable { return new DateTimeImmutable(); } }

Tests use the same interface with a fixed answer. This is the FrozenClock the test above passes in:

PHP
<?php declare(strict_types=1); namespace App\Testing; use DateTimeImmutable; use Psr\Clock\ClockInterface; final readonly class FrozenClock implements ClockInterface { private DateTimeImmutable $now; public function __construct(string $now) { $this->now = new DateTimeImmutable($now); } public function now(): DateTimeImmutable { return $this->now; } }

There are two shapes for handing time to a class that needs it. One is to pass the current moment as a method argument, and let the receiver stay clock-free entirely, the way a Reservation::checkIn(DateTimeImmutable $now) method would. The other is for a handler to own a Clock and read it when it needs the time (CheckInGuestCommand is a readonly class holding a ReservationId $reservationId, and Reservation::checkIn() is the method from the first shape; neither is shown):

PHP
<?php declare(strict_types=1); namespace App\Reservations; use Psr\Clock\ClockInterface as Clock; final readonly class CheckInGuestCommandHandler { public function __construct( private Reservations $reservations, private Clock $clock, ) {} public function handle(CheckInGuestCommand $command): void { $reservation = $this->reservations->withId($command->reservationId); $reservation->checkIn($this->clock->now()); $this->reservations->save($reservation); } }

Both shapes keep the dependency honest. The handler gets a FrozenClock in tests and a SystemClock in production; nothing in between ever calls now() on its own.

Randomness (random_int(), Str::random()) and environment reads (getenv(), $_SERVER) are hidden dependencies for the same reason, and deserve the same fix.

Two other forms of injection (and why to avoid them)

PHP has historically supported two other injection styles:

Setter injection. The class has setter methods that the container calls after construction:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use Illuminate\Contracts\Mail\Mailer; final class SendReservationConfirmation { private ?Mailer $mailer = null; public function setMailer(Mailer $mailer): void { $this->mailer = $mailer; } public function send(): void { $this->mailer->raw('Confirmed', fn () => null); } }

The class is now mutable (the mailer can be replaced after construction), and the object can exist without its dependency, so calling send() too early fails at runtime.

Property injection. Some containers, such as PHP-DI, set dependencies directly on properties using reflection and an attribute:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use DI\Attribute\Inject; use Illuminate\Contracts\Mail\Mailer; final class SendReservationConfirmation { #[Inject] private Mailer $mailer; public function send(): void { $this->mailer->raw('Confirmed', fn () => null); } }

The dependency isn't visible in the constructor, a plain new leaves the property uninitialized, and tests have to either use the container or write reflection of their own to set the property.

Constructor explosion: the real downside

The honest critique of DI is that constructors can grow large. A handler that needs eight dependencies has eight constructor parameters, and that's a lot to look at.

Two things to keep in mind:

  • Constructor explosion is a design signal, not a DI problem. A handler with eight dependencies is doing too much. Coupling and cohesion and SRP both apply. The fix is splitting the handler.

  • Small collaborators bundle related dependencies. If three dependencies are only ever used together for one step (RatePlans, TaxRates, and ExchangeRates, used only to price a stay), move that step into one collaborator, like a StayPriceCalculator, and inject that instead. The handler's constructor shrinks, and the dependencies are still explicit, one level down.

Binding interfaces to implementations

The container builds concrete classes by looking at their constructor types (autowiring), so most classes need no configuration. Interfaces are the exception: the container can't guess which implementation you want, so you bind it once, in a service provider:

PHP
<?php // Laravel declare(strict_types=1); namespace App\Providers; use App\Framework\Events\EventDispatcher; use App\Framework\Events\LaravelEventDispatcher; use App\Reservations\Infrastructure\EloquentReservations; use App\Reservations\Reservations; use App\Support\SystemClock; use Illuminate\Support\ServiceProvider; use Psr\Clock\ClockInterface; final class ReservationsServiceProvider extends ServiceProvider { public function register(): void { $this->app->bind(Reservations::class, EloquentReservations::class); $this->app->bind(EventDispatcher::class, LaravelEventDispatcher::class); $this->app->bind(ClockInterface::class, SystemClock::class); } }

Every class that asks for Reservations in its constructor gets EloquentReservations, and every class that asks for the PSR-20 ClockInterface gets SystemClock. Tests and other environments can rebind either one. Payments gets its binding in the Decorator Pattern lesson. Your business code doesn't have to know the container exists; only the service provider and the framework that boots the request do.

Pitfalls

Mixing DI and service location in the same class. Some constructors take three dependencies and then call app(...) for the fourth. The class is now half-honest about what it needs, and the reader has to check every method for the hidden half. If the dependency is real, declare it.

Injecting the container itself. public function __construct(private Container $container) makes the class dependent on everything indirectly. This is service location with extra ceremony. Inject what you need.

Container as registry of arbitrary values. Binding strings, arrays, or random instances into the container by string key is the bad version of service location. Use real config files for config, named services for services, and explicit values for everything else.

The one thing to remember

A class's constructor is the most important documentation it has. Anything that class needs to do its work should be visible in those few lines. Anything reaching into a global container, a facade, or a helper to get something the class needs is hiding a real dependency. When you see a service location call in business code, treat it as a TODO: a dependency that wants to move into the constructor.

Course Content