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

The extend method allows the modification of resolved services.

$this->app->extend(Service::class, function($service) {
    return new DecoratedService($service);
});

Laravel Service Container — Structure map

Clickable & Draggable!

Laravel Service Container — Related pages: