Service Container — Laravel

The service container is the part of Laravel that makes objects and fills their constructors. Dependency injection means a class asks for its dependencies…

Open a controller in a finished Laravel project and you'll often see a constructor asking for an object, such as NotificationService $notifier. Search the whole project for a new of that object: there isn't one. So who makes it?

The answer is the service container. The service container is the part of Laravel that knows how to make the objects in your app, including the objects that those objects need. The container then hands each object to whoever asks for it. Handing objects over through parameters is called dependency injection. Picture a library clerk who has to notify new members. The clerk only says "please send a message to Citra". The head librarian decides how the message is sent: email this week, WhatsApp next month. The clerk doesn't need new training every time the way of sending changes. In Laravel, the clerk is the controller. The clerk's words "send a message" are an interface. The head librarian's decision is a binding in AppServiceProvider: a note that says "when someone asks for this interface, make that class". Whoever hands over the right sender is the container.

Ask, don't build it yourself

A dependency is an object another object needs to do its work. MemberController needs a sender. The first way, the controller builds it itself:

public function store(Request $request)
{
    $notifier = new EmailNotification();   // locked to email
    return response()->json(['sent' => $notifier->send('Welcome!')], 201);
}

To switch to WhatsApp, or to use a fake sender in a test (code that checks your app automatically), you have to change this controller. With dependency injection, the controller just asks:

class MemberController extends Controller
{
    public function __construct(private NotificationService $notifier)
    {
    }

    public function store(Request $request)
    {
        return response()->json(['sent' => $this->notifier->send('Welcome!')], 201);
    }
}

A contract and its implementations

NotificationService is an interface, and two classes fulfil its contract:

interface NotificationService
{
    public function send(string $message): string;
}

class EmailNotification implements NotificationService
{
    public function send(string $message): string
    {
        return "Email: $message";
    }
}

class WhatsAppNotification implements NotificationService
{
    public function send(string $message): string
    {
        return "WhatsApp: $message";
    }
}

The container builds the objects

When the request POST /members comes in, the container makes the controller in these steps:

Step What the container does
1 The route needs MemberController, so the container starts making it
2 Its constructor asks for NotificationService $notifier
3 NotificationService is an interface, so the container looks up its binding: EmailNotification
4 The container makes EmailNotification, which asks for nothing through a constructor
5 That object goes into MemberController's constructor, then store() is called

The result is 201 with {"sent":"Email: Welcome!"}. A plain class (not an interface) needs no registration: the container reads its constructor on its own, then makes the objects the constructor asks for, as long as those are classes too.

Registering a binding

A binding is registered in the register() method of app/Providers/AppServiceProvider.php:

public function register(): void
{
    $this->app->bind(NotificationService::class, EmailNotification::class);
}

Without that line, step 3 cannot finish: the container doesn't know which class fulfils the contract. The request ends with status 500:

Illuminate\Contracts\Container\BindingResolutionException
Target [App\Contracts\NotificationService] is not instantiable while building [App\Http\Controllers\MemberController].

So the container doesn't stay silent, and doesn't pick a class itself: the container stops with an error.

app(...) or app()->make(...) asks the container for an object directly, just like what happens quietly in a constructor. There are two ways to register a binding. The difference shows when you ask for an object twice: $a and $b in this table are two results of app(NotificationService::class).

Registered with app(NotificationService::class) twice
$this->app->bind(...) two different objects, $a === $b is false
$this->app->singleton(...) the same object, $a === $b is true

Swapping the implementation

The head librarian switches to WhatsApp? Change one line in register():

$this->app->bind(NotificationService::class, WhatsAppNotification::class);

MemberController isn't touched, and the answer becomes {"sent":"WhatsApp: Welcome!"}. In a test, you can hand over a fake sender with $this->app->instance(NotificationService::class, new FakeNotification()), so no real message goes out (covered in the Testing lesson).

A real container in the exercise

In the exercise, you use a real container:

  1. Register EmailNotification for NotificationService with app()->bind(NotificationService::class, EmailNotification::class);.
  2. Ask for the object with app(NotificationService::class).
  3. Print the result of send("Welcome!").

In a Laravel project, bind is written in the register() of a service provider (a class such as AppServiceProvider) as $this->app->bind(...). The output must contain Email: Welcome!. The text "Email: $message" must be written inside the class EmailNotification, not added by the caller.

⚠️ Bindings that are missing, wrong, or skipped

TL;DR: The service container is the part of Laravel that makes objects and fills their constructors. Dependency injection means a class asks for its dependencies (the objects it needs) through parameters, such as __construct(private NotificationService $notifier), instead of making them with new. Plain classes are made automatically. An interface needs a binding (a note that says "this interface is filled by that class") in AppServiceProvider's register(): $this->app->bind(NotificationService::class, EmailNotification::class). Without one, the request ends with a BindingResolutionException: Target [...] is not instantiable. bind makes a new object every time it's asked, singleton reuses the same one. To swap the implementation (the class that fulfils the interface), change the binding. The controller stays the same.

⚡ Ask, don't build it yourself

Write:

class MemberController extends Controller
{
    public function __construct(private NotificationService $notifier)
    {
    }
}

Meaning: This is dependency injection: a class asks for the objects it needs through its constructor. Here it asks for NotificationService, an interface for sending messages. The service container (the part of Laravel that makes objects) makes that object and hands it over. There's no new inside the controller.

⚡ An interface needs a binding

Write:

public function register(): void
{
    $this->app->bind(NotificationService::class, EmailNotification::class);
}
Guess first: this bind line tells the container which class to make for the interface NotificationService. If that line is missing, but the controller asks for the interface, what happens?

The request ends in 500 with a BindingResolutionException: Target [...] is not instantiable. The container doesn't pick a class itself, the container stops with an error.

Meaning: This bind line is called a binding, and it is registered in AppServiceProvider's register(). A plain class needs no registration, only an interface does.

⚡ Swapping takes one line

Meaning: Moving from email to WhatsApp? Change the binding to WhatsAppNotification (another class that fulfils NotificationService), and the controller isn't touched. A binding registered with bind makes a new object every time it's asked. When it's registered with singleton, the container reuses the same object.

In the exercise, register it with app()->bind(...), ask for the object with app(NotificationService::class) (app(...) asks the container for an object), and the output must contain Email: Welcome!.

What you will learn