Service Container

    The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.

    Let's look at a simple example:

    In this example, the needs to retrieve users from a data source. So, we will inject a service that is able to retrieve users. In this context, our UserRepository most likely uses to retrieve user information from the database. However, since the repository is injected, we are able to easily swap it out with another implementation. We are also able to easily "mock", or create a dummy implementation of the UserRepository when testing our application.

    A deep understanding of the Laravel service container is essential to building a powerful, large application, as well as for contributing to the Laravel core itself.

    Almost all of your service container bindings will be registered within service providers, so most of these examples will demonstrate using the container in that context.

    Simple Bindings

    Within a service provider, you always have access to the container via the $this->app property. We can register a binding using the bind method, passing the class or interface name that we wish to register along with a Closure that returns an instance of the class:

    1. $this->app->bind('HelpSpot\API', function ($app) {
    2. return new HelpSpot\API($app->make('HttpClient'));
    3. });

    Note that we receive the container itself as an argument to the resolver. We can then use the container to resolve sub-dependencies of the object we are building.

    Binding A Singleton

    1. $this->app->singleton('HelpSpot\API', function ($app) {
    2. return new HelpSpot\API($app->make('HttpClient'));
    3. });

    Binding Instances

    You may also bind an existing object instance into the container using the instance method. The given instance will always be returned on subsequent calls into the container:

    1. $api = new HelpSpot\API(new HttpClient);
    2. $this->app->instance('HelpSpot\API', $api);

    Binding Primitives

    Sometimes you may have a class that receives some injected classes, but also needs an injected primitive value such as an integer. You may easily use contextual binding to inject any value your class may need:

    1. $this->app->when('App\Http\Controllers\UserController')
    2. ->needs('$variableName')
    3. ->give($value);

    A very powerful feature of the service container is its ability to bind an interface to a given implementation. For example, let's assume we have an EventPusher interface and a RedisEventPusher implementation. Once we have coded our RedisEventPusher implementation of this interface, we can register it with the service container like so:

    This statement tells the container that it should inject the RedisEventPusher when a class needs an implementation of EventPusher. Now we can type-hint the EventPusher interface in a constructor, or any other location where dependencies are injected by the service container:

    1. use App\Contracts\EventPusher;
    2. /**
    3. *
    4. * @param EventPusher $pusher
    5. * @return void
    6. */
    7. public function __construct(EventPusher $pusher)
    8. {
    9. $this->pusher = $pusher;
    10. }

    Sometimes you may have two classes that utilize the same interface, but you wish to inject different implementations into each class. For example, two controllers may depend on different implementations of the Illuminate\Contracts\Filesystem\Filesystem . Laravel provides a simple, fluent interface for defining this behavior:

    1. use Illuminate\Support\Facades\Storage;
    2. use App\Http\Controllers\VideoController;
    3. use Illuminate\Contracts\Filesystem\Filesystem;
    4. $this->app->when(PhotoController::class)
    5. ->needs(Filesystem::class)
    6. ->give(function () {
    7. return Storage::disk('local');
    8. });
    9. $this->app->when(VideoController::class)
    10. ->needs(Filesystem::class)
    11. ->give(function () {
    12. return Storage::disk('s3');
    13. });

    Occasionally, you may need to resolve all of a certain "category" of binding. For example, perhaps you are building a report aggregator that receives an array of many different Report interface implementations. After registering the Report implementations, you can assign them a tag using the tag method:

    1. $this->app->bind('SpeedReport', function () {
    2. //
    3. });
    4. $this->app->bind('MemoryReport', function () {
    5. //
    6. });
    7. $this->app->tag(['SpeedReport', 'MemoryReport'], 'reports');

    Once the services have been tagged, you may easily resolve them all via the tagged method:

    1. $this->app->bind('ReportAggregator', function ($app) {
    2. return new ReportAggregator($app->tagged('reports'));
    3. });

    The make Method

    You may use the make method to resolve a class instance out of the container. The make method accepts the name of the class or interface you wish to resolve:

    If you are in a location of your code that does not have access to the $app variable, you may use the global resolve helper:

    1. $api = resolve('HelpSpot\API');

    If some of your class' dependencies are not resolvable via the container, you may inject them by passing them as an associative array into the makeWith method:

    1. $api = $this->app->makeWith('HelpSpot\API', ['id' => 1]);

    Automatic Injection

    Alternatively, and importantly, you may simply "type-hint" the dependency in the constructor of a class that is resolved by the container, including , event listeners, , middleware, and more. In practice, this is how most of your objects should be resolved by the container.

    For example, you may type-hint a repository defined by your application in a controller's constructor. The repository will automatically be resolved and injected into the class:

    1. <?php
    2. use App\Users\Repository as UserRepository;
    3. class UserController extends Controller
    4. {
    5. /**
    6. * The user repository instance.
    7. */
    8. protected $users;
    9. /**
    10. * Create a new controller instance.
    11. *
    12. * @param UserRepository $users
    13. * @return void
    14. */
    15. public function __construct(UserRepository $users)
    16. {
    17. $this->users = $users;
    18. }
    19. /**
    20. * Show the user with the given ID.
    21. *
    22. * @param int $id
    23. * @return Response
    24. */
    25. public function show($id)
    26. {
    27. //
    28. }
    29. }

    The service container fires an event each time it resolves an object. You may listen to this event using the resolving method:

    1. $this->app->resolving(function ($object, $app) {
    2. // Called when container resolves object of any type...
    3. });
    4. $this->app->resolving(HelpSpot\API::class, function ($api, $app) {
    5. // Called when container resolves objects of type "HelpSpot\API"...

    As you can see, the object being resolved will be passed to the callback, allowing you to set any additional properties on the object before it is given to its consumer.