Introduction

Laravel handles managing class dependencies and dependency injection through its Service Container. Any class can have dependencies resolved using dependency injection in the class constructor. As of Laravel 5.0, this is also possible in class methods.

The service container - leveraging PHP's Reflection API - resolves concrete class implementations for you automatically.

If your class has a method called createUser, which requires an instance of UserRepository, type hint it and the service container will inject an instance for you.

What is container binding?

Unlike concrete implementations, interfaces are not instantiable. An interface describes the functionality a concrete class must implement. For example, if you were to have an interface UserRepository and type hint against this in your class:

// app/Contracts/UserRepository.php

namespace App\Contracts\Repositories;

interface UserRepository
{
    public function create(array $data);
}

// app/Http/Controllers/UserController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Contracts\Repositories\UserRepository;

class UserController extends Controller
{
    protected $repository;

    public function __construct(UserRepository $repository)
    {
        $this->repository = $repository;
    }

    public function store(Request $request)
    {
        $this->repository->create($request->all());
    }
}

Without binding a concrete implementation to the container you'll encounter a BindingResolutionException accessing the store method. The service container will resolve the interface dependency in the __construct method, but an interface cannot be instantiated.

Target [App\Contracts\Repositories\UserRepository] is not instantiable.

How does it work?

Using container binding lets you tell the service container that when the application asks for UserRepository, it should return a specific class, rather than the interface itself. The container is capable of resolving concrete objects using PHP's reflection API, so you should only bind classes that depend on interfaces.

// app/Providers/AppServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Repositories\EloquentUserRepository;
use App\Contracts\Repositories\UserRepository;

class AppServiceProvider
{
    public function register()
    {
        $this->app->bind(UserRepository::class, EloquentUserRepository::class);
    }
}

// app/Repositories/UserRepository.php

namespace App\Repositories;

use App\User;
use App\Contracts\Repositories\UserRepository;

class EloquentUserRepository implements UserRepository
{
    public function create(array $data)
    {
        return User::create($data);
    }
}

Now, any time the UserRepository interface is needed by your application, the service container will inject an instance of EloquentUserRepository.

This makes swapping the persistence layer in this instance easier1 in future. If you type hint the UserRepository interface throughout your application, should you ever need a different implementation just update the binding and the container will handle the rest. The application shouldn't care how the UserRepository is implemented, just that it is.

What about many implementations of an interface?

Container binding works well when you only have one implementation of an interface at any given time. What about when you have many concrete implementations in use simultaneously? Consider working with Socialite to connect with Twitter and Instagram.

A registered user of your application can connect their Twitter or Instagram accounts to their account. You can create an AuthenticateTwitterUser and AuthenticateInstagramUser class that each implement an AuthenticateSocialUser interface. Depending on the provider you need to connect with, you can bind the relevant implementation and inject it at run time.

When you type hint a concrete class to a constructor, this couples your business logic to it. There must be A Better Way ™. Of course there is a better way.

Enter contextual container binding

The service container can resolve a class depending on which context requested it using contextual container binding, decoupling your business logic.


// app/Providers/AppServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Social\Connect\AuthenticateTwitterUser;
use App\Social\Connect\AuthenticateInstagramUser;
use App\Http\Controllers\Connect\TwitterAuthController;
use App\Contracts\Social\Connect\AuthenticateSocialUser;
use App\Http\Controllers\Connect\InstagramAuthController;

class AppServiceProvider extends ServiceProvider
{
    // ...
    public function register()
    {
        $this->app->when(TwitterAuthController::class)
                  ->needs(AuthenticateSocialUser::class)
                  ->give(AuthenticateTwitterUser::class);

        $this->app->when(InstagramAuthController::class)
                  ->needs(AuthenticateSocialUser::class)
                  ->give(AuthenticateInstagramUser::class);
    }
}

Now you can keep controllers slim, using inheritance to share common functionality and define only the methods that differ between providers. For example, Twitter and Instagram return different parameters in their callback, so you would extract the callback handling to separate controllers to facilitate this.

Conclusion

Container binding lets you manage dependencies across your entire application from one place. Contextual binding resolves many interface implementations for distinct use cases throughout your application.

Note: Contextual container binding only works for dependencies declared in the __construct method. It does not work for method injection and it was never the intention to do so. This raises an interesting question; should you have many distinct implementations of an interface within a single class? I would suggest that this might be the point at which you identify whether or not you should be breaking the class down into separate concerns.

1: Switching your persistence layer isn't as simple as changing from EloquentUserRepository to MongoUserRepository. You still need to ensure that you're still returning the same data in both instances. This illustrates that switching application bindings is much easier when type hinting an interface.