Laravel Service Container
Laravel Service Container
Laravel Service Container — Is a powerful tool for managing class dependencies and performing dependency injection.
The Laravel service container is used to resolve all Laravel controllers.
Almost all of its bindings will be registered within service providers.
Service Container: Simple Bindings
$this->app->bind('HelpSpot\API', function ($app) {
return new HelpSpot\API($app->make('HttpClient'));
});
Service Container: Binding A Singleton
$this->app->singleton('HelpSpot\API', function ($app) {
return new HelpSpot\API($app->make('HttpClient'));
});
Service Container: Binding Instances
$api = new HelpSpot\API(new HttpClient);
$this->app->instance('HelpSpot\API', $api);
Service Container: Binding Primitives
$this->app->when('App\Http\Controllers\UserController')
->needs('$variableName')
->give($value);
Service Container: Binding Interfaces To Implementations
$this->app->bind(
'App\Contracts\EventPusher',
'App\Services\RedisEventPusher'
);
Use App\Contracts\EventPusher;
/**
* Create a new class instance.
*
* @param EventPusher $pusher
* @return void
*/
public function __construct(EventPusher $pusher)
{
$this->pusher = $pusher;
}
Service Container: Contextual Binding
Sometimes you may have two classes that utilize the same interface, but you wish to inject different implementations into each class.
Use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\PhotoController;
use App\Http\Controllers\VideoController;
use Illuminate\Contracts\Filesystem\Filesystem;
$this->app->when(PhotoController::class)
->needs(Filesystem::class)
->give(function () {
return Storage::disk('local');
});
$this->app->when(VideoController::class)
->needs(Filesystem::class)
->give(function () {
return Storage::disk('s3');
});
Service Container: Tagging
Once the services have been tagged, you may easily resolve them all via the tagged method.
$this->app->bind('SpeedReport', function () {
//
});
$this->app->bind('MemoryReport', function () {
//
});
$this->app->tag(['SpeedReport', 'MemoryReport'], 'reports');
$this->app->bind('ReportAggregator', function ($app) {
return new ReportAggregator($app->tagged('reports'));
});
Service Container: Extending Bindings
Related concepts
- Laravel Facades
- Laravel Service Container: Service Container: Simple Bindings
- Laravel Service Container: Service Container: Binding A Singleton
- Laravel Service Container: Service Container: Binding Instances
- Laravel Service Container: Service Container: Binding Primitives
- Laravel Service Container: Service Container: Binding Interfaces To Implementations
- Laravel Service Container: Service Container: Contextual Binding
- Laravel Service Container: Service Container: Tagging
- Laravel Service Container: Service Container: Extending Bindings
- Laravel Views: View Composers
- When To Use Facades: Facades Vs. Dependency Injection