Service Container

Introduction

The Laravel service container is a powerful tool for managing class dependencies. Dependency injection is a fancy word 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:

  1. <?php namespace App\Handlers\Commands;
  2. use App\User;
  3. use App\Commands\PurchasePodcastCommand;
  4. use Illuminate\Contracts\Mail\Mailer;
  5. class PurchasePodcastHandler {
  6. /**
  7. * The mailer implementation.
  8. */
  9. protected $mailer;
  10. /**
  11. * Create a new instance.
  12. *
  13. * @param Mailer $mailer
  14. * @return void
  15. */
  16. public function __construct(Mailer $mailer)
  17. {
  18. $this->mailer = $mailer;
  19. }
  20. /**
  21. * Purchase a podcast.
  22. *
  23. * @param PurchasePodcastCommand $command
  24. * @return void
  25. */
  26. public function handle(PurchasePodcastCommand $command)
  27. {
  28. //
  29. }
  30. }

In this example, the PurchasePodcast command handler needs to send e-mails when a podcast is purchased. So, we will inject a service that is able to send e-mails. Since the service 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 mailer 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.

Basic Usage

Binding

Almost all of your service container bindings will be registered within service providers, so all of these examples will demonstrate using the container in that context. However, if you need an instance of the container elsewhere in your application, such as a factory, you may type-hint the Illuminate\Contracts\Container\Container contract and an instance of the container will be injected for you. Alternatively, you may use the App facade to access the container.

Registering A Basic Resolver

Within a service provider, you always have access to the container via the $this->app instance variable.

There are several ways the service container can register dependencies, including Closure callbacks and binding interfaces to implementations. First, we'll explore Closure callbacks. A Closure resolver is registered in the container with a key (typically the class name) and a Closure that returns some value:

  1. $this->app->bind('FooBar', function($app)
  2. {
  3. return new FooBar($app['SomethingElse']);
  4. });

Registering A Singleton

Sometimes, you may wish to bind something into the container that should only be resolved once, and the same instance should be returned on subsequent calls into the container:

  1. $this->app->singleton('FooBar', function($app)
  2. {
  3. return new FooBar($app['SomethingElse']);
  4. });

Binding An Existing Instance Into The Container

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. $fooBar = new FooBar(new SomethingElse);
  2. $this->app->instance('FooBar', $fooBar);

Resolving

There are several ways to resolve something out of the container. First, you may use the make method:

  1. $fooBar = $this->app->make('FooBar');

Secondly, you may use "array access" on the container, since it implements PHP's ArrayAccess interface:

  1. $fooBar = $this->app['FooBar'];

Lastly, but most importantly, you may simply "type-hint" the dependency in the constructor of a class that is resolved by the container, including controllers, event listeners, queue jobs, filters, and more. The container will automatically inject the dependencies:

  1. <?php namespace App\Http\Controllers;
  2. use Illuminate\Routing\Controller;
  3. use App\Users\Repository as UserRepository;
  4. class UserController extends Controller {
  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. }

Binding Interfaces To Implementations

Injecting Concrete Dependencies

A very powerful feature of the service container is its ability to bind an interface to a given implementation. For example, perhaps our application integrates with the Pusher web service for sending and receiving real-time events. If we are using Pusher's PHP SDK, we could inject an instance of the Pusher client into a class:

  1. <?php namespace App\Handlers\Commands;
  2. use App\Commands\CreateOrder;
  3. use Pusher\Client as PusherClient;
  4. class CreateOrderHandler {
  5. /**
  6. * The Pusher SDK client instance.
  7. */
  8. protected $pusher;
  9. /**
  10. * Create a new order handler instance.
  11. *
  12. * @param PusherClient $pusher
  13. * @return void
  14. */
  15. public function __construct(PusherClient $pusher)
  16. {
  17. $this->pusher = $pusher;
  18. }
  19. /**
  20. * Execute the given command.
  21. *
  22. * @param CreateOrder $command
  23. * @return void
  24. */
  25. public function execute(CreateOrder $command)
  26. {
  27. //
  28. }
  29. }

In this example, it is good that we are injecting the class dependencies; however, we are tightly coupled to the Pusher SDK. If the Pusher SDK methods change or we decide to switch to a new event service entirely, we will need to change our CreateOrderHandler code.

Program To An Interface

In order to "insulate" the CreateOrderHandler against changes to event pushing, we could define an EventPusher interface and a PusherEventPusher implementation:

  1. <?php namespace App\Contracts;
  2. interface EventPusher {
  3. /**
  4. * Push a new event to all clients.
  5. *
  6. * @param string $event
  7. * @param array $data
  8. * @return void
  9. */
  10. public function push($event, array $data);
  11. }

Once we have coded our PusherEventPusher implementation of this interface, we can register it with the service container like so:

  1. $this->app->bind('App\Contracts\EventPusher', 'App\Services\PusherEventPusher');

This tells the container that it should inject the PusherEventPusher when a class needs an implementation of EventPusher. Now we can type-hint the EventPusher interface in our constructor:

  1. /**
  2. * Create a new order handler instance.
  3. *
  4. * @param EventPusher $pusher
  5. * @return void
  6. */
  7. public function __construct(EventPusher $pusher)
  8. {
  9. $this->pusher = $pusher;
  10. }

Contextual Binding

Sometimes you may have two classes that utilize the same interface, but you wish to inject different implementations into each class. For example, when our system receives a new Order, we may want to send an event via PubNub rather than Pusher. Laravel provides a simple, fluent interface for defining this behavior:

  1. $this->app->when('App\Handlers\Commands\CreateOrderHandler')
  2. ->needs('App\Contracts\EventPusher')
  3. ->give('App\Services\PubNubEventPusher');

Tagging

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. });
  5. $this->app->bind('MemoryReport', function()
  6. {
  7. //
  8. });
  9. $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. {
  3. return new ReportAggregator($app->tagged('reports'));
  4. });

Practical Applications

Laravel provides several opportunities to use the service container to increase the flexibility and testability of your application. One primary example is when resolving controllers. All controllers are resolved through the service container, meaning you can type-hint dependencies in a controller constructor, and they will automatically be injected.

  1. <?php namespace App\Http\Controllers;
  2. use Illuminate\Routing\Controller;
  3. use App\Repositories\OrderRepository;
  4. class OrdersController extends Controller {
  5. /**
  6. * The order repository instance.
  7. */
  8. protected $orders;
  9. /**
  10. * Create a controller instance.
  11. *
  12. * @param OrderRepository $orders
  13. * @return void
  14. */
  15. public function __construct(OrderRepository $orders)
  16. {
  17. $this->orders = $orders;
  18. }
  19. /**
  20. * Show all of the orders.
  21. *
  22. * @return Response
  23. */
  24. public function index()
  25. {
  26. $orders = $this->orders->all();
  27. return view('orders', ['orders' => $orders]);
  28. }
  29. }

In this example, the OrderRepository class will automatically be injected into the controller. This means that a "mock" OrderRepository may be bound into the container when unit testing, allowing for painless stubbing of database layer interaction.

Other Examples Of Container Usage

Of course, as mentioned above, controllers are not the only classes Laravel resolves via the service container. You may also type-hint dependencies on route Closures, filters, queue jobs, event listeners, and more. For examples of using the service container in these contexts, please refer to their documentation.

Container Events

Registering A Resolving Listener

The 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. {
  3. // Called when container resolves object of any type...
  4. });
  5. $this->app->resolving(function(FooBar $fooBar, $app)
  6. {
  7. // Called when container resolves objects of type "FooBar"...
  8. });

The object being resolved will be passed to the callback.