Service Container
Introduction
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:
1<?php23namespace App\Http\Controllers;45use App\Http\Controllers\Controller;6use App\Repositories\UserRepository;7use App\Models\User;89class UserController extends Controller10{11 /**12 * The user repository implementation.13 *14 * @var UserRepository15 */16 protected $users;1718 /**19 * Create a new controller instance.20 *21 * @param UserRepository $users22 * @return void23 */24 public function __construct(UserRepository $users)25 {26 $this->users = $users;27 }2829 /**30 * Show the profile for the given user.31 *32 * @param int $id33 * @return Response34 */35 public function show($id)36 {37 $user = $this->users->find($id);3839 return view('user.profile', ['user' => $user]);40 }41}
1<?php23namespace App\Http\Controllers;45use App\Http\Controllers\Controller;6use App\Repositories\UserRepository;7use App\Models\User;89class UserController extends Controller10{11 /**12 * The user repository implementation.13 *14 * @var UserRepository15 */16 protected $users;1718 /**19 * Create a new controller instance.20 *21 * @param UserRepository $users22 * @return void23 */24 public function __construct(UserRepository $users)25 {26 $this->users = $users;27 }2829 /**30 * Show the profile for the given user.31 *32 * @param int $id33 * @return Response34 */35 public function show($id)36 {37 $user = $this->users->find($id);3839 return view('user.profile', ['user' => $user]);40 }41}
In this example, the UserController
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 Eloquent 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.
Zero Configuration Resolution
If a class has no dependencies or only depends on other concrete classes (not interfaces), the container does not need to be instructed on how to resolve that class. For example, you may place the following code in your routes/web.php
file:
1<?php23class Service4{5 //6}78Route::get('/', function (Service $service) {9 die(get_class($service));10});
1<?php23class Service4{5 //6}78Route::get('/', function (Service $service) {9 die(get_class($service));10});
In this example, hitting your application's /
route will automatically resolve the Service
class and inject it into your route's handler. This is game changing. It means you can develop your application and take advantage of dependency injection without worrying about bloated configuration files.
Thankfully, many of the classes you will be writing when building a Laravel application automatically receive their dependencies via the container, including controllers, event listeners, middleware, and more. Additionally, you may type-hint dependencies in the handle
method of queued jobs. Once you taste the power of automatic and zero configuration dependency injection it feels impossible to develop without it.
When To Use The Container
Thanks to zero configuration resolution, you will often type-hint dependencies on routes, controllers, event listeners, and elsewhere without ever manually interacting with the container. For example, you might type-hint the Illuminate\Http\Request
object on your route definition so that you can easily access the current request. Even though we never have to interact with the container to write this code, it is managing the injection of these dependencies behind the scenes:
1use Illuminate\Http\Request;23Route::get('/', function (Request $request) {4 // ...5});
1use Illuminate\Http\Request;23Route::get('/', function (Request $request) {4 // ...5});
In many cases, thanks to automatic dependency injection and facades, you can build Laravel applications without ever manually binding or resolving anything from the container. So, when would you ever manually interact with the container? Let's examine two situations.
First, if you write a class that implements an interface and you wish to type-hint that interface on a route or class constructor, you must tell the container how to resolve that interface. Secondly, if you are writing a Laravel package that you plan to share with other Laravel developers, you may need to bind your package's services into the container.
Binding
Binding Basics
Simple Bindings
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.
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:
1use App\Services\Transistor;2use App\Services\PodcastParser;34$this->app->bind(Transistor::class, function ($app) {5 return new Transistor($app->make(PodcastParser::class));6});
1use App\Services\Transistor;2use App\Services\PodcastParser;34$this->app->bind(Transistor::class, function ($app) {5 return new Transistor($app->make(PodcastParser::class));6});
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.
As mentioned, you will typically be interacting with the container within service providers; however, if you would like to interact with the container outside of a service provider, you may do so via the App
facade:
1use App\Services\Transistor;2use Illuminate\Support\Facades\App;34App::bind(Transistor::class, function ($app) {5 // ...6});
1use App\Services\Transistor;2use Illuminate\Support\Facades\App;34App::bind(Transistor::class, function ($app) {5 // ...6});
There is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects, since it can automatically resolve these objects using reflection.
Binding A Singleton
The singleton
method binds a class or interface into the container that should only be resolved one time. Once a singleton binding is resolved, the same object instance will be returned on subsequent calls into the container:
1use App\Services\Transistor;2use App\Services\PodcastParser;34$this->app->singleton(Transistor::class, function ($app) {5 return new Transistor($app->make(PodcastParser::class));6});
1use App\Services\Transistor;2use App\Services\PodcastParser;34$this->app->singleton(Transistor::class, function ($app) {5 return new Transistor($app->make(PodcastParser::class));6});
Binding Scoped Singletons
The scoped
method binds a class or interface into the container that should only be resolved one time within a given Laravel request / job lifecycle. While this method is similar to the singleton
method, instances registered using the scoped
method will be flushed whenever the Laravel application starts a new "lifecycle", such as when a Laravel Octane worker processes a new request or when a Laravel queue worker processes a new job:
1use App\Services\Transistor;2use App\Services\PodcastParser;34$this->app->scoped(Transistor::class, function ($app) {5 return new Transistor($app->make(PodcastParser::class));6});
1use App\Services\Transistor;2use App\Services\PodcastParser;34$this->app->scoped(Transistor::class, function ($app) {5 return new Transistor($app->make(PodcastParser::class));6});
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:
1use App\Services\Transistor;2use App\Services\PodcastParser;34$service = new Transistor(new PodcastParser);56$this->app->instance(Transistor::class, $service);
1use App\Services\Transistor;2use App\Services\PodcastParser;34$service = new Transistor(new PodcastParser);56$this->app->instance(Transistor::class, $service);
Binding Interfaces To Implementations
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:
1use App\Contracts\EventPusher;2use App\Services\RedisEventPusher;34$this->app->bind(EventPusher::class, RedisEventPusher::class);
1use App\Contracts\EventPusher;2use App\Services\RedisEventPusher;34$this->app->bind(EventPusher::class, RedisEventPusher::class);
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 the constructor of a class that is resolved by the container. Remember, controllers, event listeners, middleware, and various other types of classes within Laravel applications are always resolved using the container:
1use App\Contracts\EventPusher;23/**4 * Create a new class instance.5 *6 * @param \App\Contracts\EventPusher $pusher7 * @return void8 */9public function __construct(EventPusher $pusher)10{11 $this->pusher = $pusher;12}
1use App\Contracts\EventPusher;23/**4 * Create a new class instance.5 *6 * @param \App\Contracts\EventPusher $pusher7 * @return void8 */9public function __construct(EventPusher $pusher)10{11 $this->pusher = $pusher;12}
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, two controllers may depend on different implementations of the Illuminate\Contracts\Filesystem\Filesystem
contract. Laravel provides a simple, fluent interface for defining this behavior:
1use App\Http\Controllers\PhotoController;2use App\Http\Controllers\UploadController;3use App\Http\Controllers\VideoController;4use Illuminate\Contracts\Filesystem\Filesystem;5use Illuminate\Support\Facades\Storage;67$this->app->when(PhotoController::class)8 ->needs(Filesystem::class)9 ->give(function () {10 return Storage::disk('local');11 });1213$this->app->when([VideoController::class, UploadController::class])14 ->needs(Filesystem::class)15 ->give(function () {16 return Storage::disk('s3');17 });
1use App\Http\Controllers\PhotoController;2use App\Http\Controllers\UploadController;3use App\Http\Controllers\VideoController;4use Illuminate\Contracts\Filesystem\Filesystem;5use Illuminate\Support\Facades\Storage;67$this->app->when(PhotoController::class)8 ->needs(Filesystem::class)9 ->give(function () {10 return Storage::disk('local');11 });1213$this->app->when([VideoController::class, UploadController::class])14 ->needs(Filesystem::class)15 ->give(function () {16 return Storage::disk('s3');17 });
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:
1use App\Http\Controllers\UserController;23$this->app->when(UserController::class)4 ->needs('$variableName')5 ->give($value);
1use App\Http\Controllers\UserController;23$this->app->when(UserController::class)4 ->needs('$variableName')5 ->give($value);
Sometimes a class may depend on an array of tagged instances. Using the giveTagged
method, you may easily inject all of the container bindings with that tag:
1$this->app->when(ReportAggregator::class)2 ->needs('$reports')3 ->giveTagged('reports');
1$this->app->when(ReportAggregator::class)2 ->needs('$reports')3 ->giveTagged('reports');
If you need to inject a value from one of your application's configuration files, you may use the giveConfig
method:
1$this->app->when(ReportAggregator::class)2 ->needs('$timezone')3 ->giveConfig('app.timezone');
1$this->app->when(ReportAggregator::class)2 ->needs('$timezone')3 ->giveConfig('app.timezone');
Binding Typed Variadics
Occasionally, you may have a class that receives an array of typed objects using a variadic constructor argument:
1<?php23use App\Models\Filter;4use App\Services\Logger;56class Firewall7{8 /**9 * The logger instance.10 *11 * @var \App\Services\Logger12 */13 protected $logger;1415 /**16 * The filter instances.17 *18 * @var array19 */20 protected $filters;2122 /**23 * Create a new class instance.24 *25 * @param \App\Services\Logger $logger26 * @param array $filters27 * @return void28 */29 public function __construct(Logger $logger, Filter ...$filters)30 {31 $this->logger = $logger;32 $this->filters = $filters;33 }34}
1<?php23use App\Models\Filter;4use App\Services\Logger;56class Firewall7{8 /**9 * The logger instance.10 *11 * @var \App\Services\Logger12 */13 protected $logger;1415 /**16 * The filter instances.17 *18 * @var array19 */20 protected $filters;2122 /**23 * Create a new class instance.24 *25 * @param \App\Services\Logger $logger26 * @param array $filters27 * @return void28 */29 public function __construct(Logger $logger, Filter ...$filters)30 {31 $this->logger = $logger;32 $this->filters = $filters;33 }34}
Using contextual binding, you may resolve this dependency by providing the give
method with a closure that returns an array of resolved Filter
instances:
1$this->app->when(Firewall::class)2 ->needs(Filter::class)3 ->give(function ($app) {4 return [5 $app->make(NullFilter::class),6 $app->make(ProfanityFilter::class),7 $app->make(TooLongFilter::class),8 ];9 });
1$this->app->when(Firewall::class)2 ->needs(Filter::class)3 ->give(function ($app) {4 return [5 $app->make(NullFilter::class),6 $app->make(ProfanityFilter::class),7 $app->make(TooLongFilter::class),8 ];9 });
For convenience, you may also just provide an array of class names to be resolved by the container whenever Firewall
needs Filter
instances:
1$this->app->when(Firewall::class)2 ->needs(Filter::class)3 ->give([4 NullFilter::class,5 ProfanityFilter::class,6 TooLongFilter::class,7 ]);
1$this->app->when(Firewall::class)2 ->needs(Filter::class)3 ->give([4 NullFilter::class,5 ProfanityFilter::class,6 TooLongFilter::class,7 ]);
Variadic Tag Dependencies
Sometimes a class may have a variadic dependency that is type-hinted as a given class (Report ...$reports
). Using the needs
and giveTagged
methods, you may easily inject all of the container bindings with that tag for the given dependency:
1$this->app->when(ReportAggregator::class)2 ->needs(Report::class)3 ->giveTagged('reports');
1$this->app->when(ReportAggregator::class)2 ->needs(Report::class)3 ->giveTagged('reports');
Tagging
Occasionally, you may need to resolve all of a certain "category" of binding. For example, perhaps you are building a report analyzer 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(CpuReport::class, function () {2 //3});45$this->app->bind(MemoryReport::class, function () {6 //7});89$this->app->tag([CpuReport::class, MemoryReport::class], 'reports');
1$this->app->bind(CpuReport::class, function () {2 //3});45$this->app->bind(MemoryReport::class, function () {6 //7});89$this->app->tag([CpuReport::class, MemoryReport::class], 'reports');
Once the services have been tagged, you may easily resolve them all via the container's tagged
method:
1$this->app->bind(ReportAnalyzer::class, function ($app) {2 return new ReportAnalyzer($app->tagged('reports'));3});
1$this->app->bind(ReportAnalyzer::class, function ($app) {2 return new ReportAnalyzer($app->tagged('reports'));3});
Extending Bindings
The extend
method allows the modification of resolved services. For example, when a service is resolved, you may run additional code to decorate or configure the service. The extend
method accepts two arguments, the service class you're extending and a closure that should return the modified service. The closure receives the service being resolved and the container instance:
1$this->app->extend(Service::class, function ($service, $app) {2 return new DecoratedService($service);3});
1$this->app->extend(Service::class, function ($service, $app) {2 return new DecoratedService($service);3});
Resolving
The make
Method
You may use the make
method to resolve a class instance from the container. The make
method accepts the name of the class or interface you wish to resolve:
1use App\Services\Transistor;23$transistor = $this->app->make(Transistor::class);
1use App\Services\Transistor;23$transistor = $this->app->make(Transistor::class);
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. For example, we may manually pass the $id
constructor argument required by the Transistor
service:
1use App\Services\Transistor;23$transistor = $this->app->makeWith(Transistor::class, ['id' => 1]);
1use App\Services\Transistor;23$transistor = $this->app->makeWith(Transistor::class, ['id' => 1]);
If you are outside of a service provider in a location of your code that does not have access to the $app
variable, you may use the App
facade or the app
helper to resolve a class instance from the container:
1use App\Services\Transistor;2use Illuminate\Support\Facades\App;34$transistor = App::make(Transistor::class);56$transistor = app(Transistor::class);
1use App\Services\Transistor;2use Illuminate\Support\Facades\App;34$transistor = App::make(Transistor::class);56$transistor = app(Transistor::class);
If you would like to have the Laravel container instance itself injected into a class that is being resolved by the container, you may type-hint the Illuminate\Container\Container
class on your class' constructor:
1use Illuminate\Container\Container;23/**4 * Create a new class instance.5 *6 * @param \Illuminate\Container\Container $container7 * @return void8 */9public function __construct(Container $container)10{11 $this->container = $container;12}
1use Illuminate\Container\Container;23/**4 * Create a new class instance.5 *6 * @param \Illuminate\Container\Container $container7 * @return void8 */9public function __construct(Container $container)10{11 $this->container = $container;12}
Automatic Injection
Alternatively, and importantly, you may type-hint the dependency in the constructor of a class that is resolved by the container, including controllers, event listeners, middleware, and more. Additionally, you may type-hint dependencies in the handle
method of queued jobs. 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<?php23namespace App\Http\Controllers;45use App\Repositories\UserRepository;67class UserController extends Controller8{9 /**10 * The user repository instance.11 *12 * @var \App\Repositories\UserRepository13 */14 protected $users;1516 /**17 * Create a new controller instance.18 *19 * @param \App\Repositories\UserRepository $users20 * @return void21 */22 public function __construct(UserRepository $users)23 {24 $this->users = $users;25 }2627 /**28 * Show the user with the given ID.29 *30 * @param int $id31 * @return \Illuminate\Http\Response32 */33 public function show($id)34 {35 //36 }37}
1<?php23namespace App\Http\Controllers;45use App\Repositories\UserRepository;67class UserController extends Controller8{9 /**10 * The user repository instance.11 *12 * @var \App\Repositories\UserRepository13 */14 protected $users;1516 /**17 * Create a new controller instance.18 *19 * @param \App\Repositories\UserRepository $users20 * @return void21 */22 public function __construct(UserRepository $users)23 {24 $this->users = $users;25 }2627 /**28 * Show the user with the given ID.29 *30 * @param int $id31 * @return \Illuminate\Http\Response32 */33 public function show($id)34 {35 //36 }37}
Method Invocation & Injection
Sometimes you may wish to invoke a method on an object instance while allowing the container to automatically inject that method's dependencies. For example, given the following class:
1<?php23namespace App;45use App\Repositories\UserRepository;67class UserReport8{9 /**10 * Generate a new user report.11 *12 * @param \App\Repositories\UserRepository $repository13 * @return array14 */15 public function generate(UserRepository $repository)16 {17 // ...18 }19}
1<?php23namespace App;45use App\Repositories\UserRepository;67class UserReport8{9 /**10 * Generate a new user report.11 *12 * @param \App\Repositories\UserRepository $repository13 * @return array14 */15 public function generate(UserRepository $repository)16 {17 // ...18 }19}
You may invoke the generate
method via the container like so:
1use App\UserReport;2use Illuminate\Support\Facades\App;34$report = App::call([new UserReport, 'generate']);
1use App\UserReport;2use Illuminate\Support\Facades\App;34$report = App::call([new UserReport, 'generate']);
The call
method accepts any PHP callable. The container's call
method may even be used to invoke a closure while automatically injecting its dependencies:
1use App\Repositories\UserRepository;2use Illuminate\Support\Facades\App;34$result = App::call(function (UserRepository $repository) {5 // ...6});
1use App\Repositories\UserRepository;2use Illuminate\Support\Facades\App;34$result = App::call(function (UserRepository $repository) {5 // ...6});
Container Events
The service container fires an event each time it resolves an object. You may listen to this event using the resolving
method:
1use App\Services\Transistor;23$this->app->resolving(Transistor::class, function ($transistor, $app) {4 // Called when container resolves objects of type "Transistor"...5});67$this->app->resolving(function ($object, $app) {8 // Called when container resolves object of any type...9});
1use App\Services\Transistor;23$this->app->resolving(Transistor::class, function ($transistor, $app) {4 // Called when container resolves objects of type "Transistor"...5});67$this->app->resolving(function ($object, $app) {8 // Called when container resolves object of any type...9});
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.
PSR-11
Laravel's service container implements the PSR-11 interface. Therefore, you may type-hint the PSR-11 container interface to obtain an instance of the Laravel container:
1use App\Services\Transistor;2use Psr\Container\ContainerInterface;34Route::get('/', function (ContainerInterface $container) {5 $service = $container->get(Transistor::class);67 //8});
1use App\Services\Transistor;2use Psr\Container\ContainerInterface;34Route::get('/', function (ContainerInterface $container) {5 $service = $container->get(Transistor::class);67 //8});
An exception is thrown if the given identifier can't be resolved. The exception will be an instance of Psr\Container\NotFoundExceptionInterface
if the identifier was never bound. If the identifier was bound but was unable to be resolved, an instance of Psr\Container\ContainerExceptionInterface
will be thrown.