Skip to content
Tutorials Center
My learning

Topics

Lesson 115 of 147 ยท Advanced PHP

Dependency Injection and Containers

Learn constructor injection in PHP, why it beats hidden dependencies, and how to build a small PSR-11 style container with bind, get and autowiring.

Every class depends on something: a mailer, a database connection, a clock, a logger. The question is where those objects come from. If a class creates them itself with new, or reaches out to a global, the dependency is hidden and locked in. If the class simply asks for them in its constructor, the caller decides. That second approach is dependency injection (DI), and it is the single most useful design habit in modern PHP.

DI is a technique, not a library. You can practice it with no framework at all. A container is a helper that automates the boring part: building objects and handing them their dependencies. In this lesson you will see the problem, fix it with constructor injection, and then write a tiny container in the spirit of PSR-11, the standard interface that Laravel, Symfony and most other frameworks follow.

This lesson builds on interfaces, constructors, Reflection and the design patterns lesson, which showed the singleton problem in brief.

The problem: hidden dependencies

Look at a class that builds its own collaborators:

PHP A class that creates its own dependencies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

WelcomeService works, but you cannot test it without sending real mail, and you cannot switch to another mailer without editing the class. Its constructor says "I need nothing", which is a lie. The real dependency is buried inside a method.

Constructor injection

The fix: declare what you need as a constructor parameter, typed against an interface. Combined with constructor promotion it is very short:

PHP Constructor injection with an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Now the dependency is visible in the class signature, replaceable in tests, and WelcomeService no longer knows which mailer it gets. This is the "depend on abstractions" idea from OOP Design Principles.

flowchart LR
    C["Caller / composition root"] -->|creates| M["SmtpMailer"]
    C -->|creates and passes M| S["WelcomeService"]
    S -->|uses via Mailer interface| M

The code that builds the object graph (the composition root) is the only place that knows the concrete classes.

Other injection styles exist (setters, method parameters), but prefer the constructor: an object is complete the moment it exists, and its dependencies can be private readonly.

Wiring by hand gets long

With ten services, the wiring code at the top of your application becomes a long list of new calls in the right order. That is fine for small apps, and still the clearest option. When it grows, a container takes over.

A tiny PSR-11 style container

PSR-11 defines just two methods: get(string $id) returns an entry and has(string $id) says whether one exists. Missing entries throw an exception. Here is a minimal container with three abilities: store a factory (bind), build once and reuse (singleton), and autowire classes it was never told about by reading constructor types with Reflection.

PHP A small container with autowiring

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Autowiring needs a hint only for things Reflection cannot guess: an interface (which implementation?) or a scalar such as a DSN string. Everything else is built by following type declarations, recursively.

sequenceDiagram
    participant App
    participant C as Container
    App->>C: get(WelcomeService)
    C->>C: read constructor types
    C->>C: get(Mailer) via bound factory
    C->>C: get(Clock) via autowiring
    C-->>App: new WelcomeService(mailer, clock)

Autowiring resolves each constructor parameter by asking the container again, so whole graphs build themselves.

A production container adds more: detecting circular dependencies, caching the reflection results, compiling the wiring into plain PHP. That is why you normally use PHP-DI, Symfony's container or Laravel's rather than your own. Because they all implement PSR-11, the way you ask for things is the same.

Service locator: the trap

A container is allowed in exactly one kind of place: the composition root (your entry point, a router that builds controllers). If you pass the container into your classes and call $container->get(Mailer::class) inside methods, you have a service locator. It looks like DI but the dependencies are hidden again, and your classes now depend on the container itself. Always inject the specific things a class needs.

Also watch for constructor bloat: if a class needs eight dependencies it probably does too much. Splitting it is a better fix than hiding the problem with a container.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What makes constructor injection better than creating a dependency with new inside a method?

    Injecting the dependency makes it explicit and swappable. Speed is unaffected, and interfaces are what make the swap practical.
  2. 2. In the lesson's container, why does Mailer::class need an explicit singleton() registration while Clock::class does not?

    Reflection can instantiate a concrete class from its constructor types, but an interface has no constructor to read. Someone must say which implementation to use.
  3. 3. What is the service locator anti-pattern?

    Passing the container around hides what each class needs and couples every class to the container. Keep the container at the composition root.
  4. 4. What does PSR-11 standardize?

    PSR-11 defines the ContainerInterface so libraries can fetch services from any compliant container.

Summary

  • Dependency injection means a class receives its collaborators instead of creating or fetching them.
  • Prefer constructor injection with interface types; the dependency becomes visible, and tests can pass fakes.
  • A container builds object graphs; PSR-11 standardizes get() and has().
  • Autowiring reads constructor types with Reflection; interfaces and scalars need explicit configuration.
  • Keep the container at the composition root, and avoid the service locator pattern.
  • If a constructor takes too many parameters, split the class.

Next: Events and Listeners