Laravel Service Container: Service Container: Contextual Binding

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');
          });

Related concepts

Service Container: Contextual Binding

Laravel Service Container: Service Container: Contextual Binding — Structure map

Clickable & Draggable!

Laravel Service Container: Service Container: Contextual Binding — Related pages: