Laravel contextual binding to be more specific to methods rather then class only

312 Views Asked by At

I am trying to understand laravel bind. let's say, I have UploadFileController.php

Route::post('/upload/images', 'UploadFilesController@uploadImage');
Route::post('/upload/pdf', 'UploadFilesController@uploadPdf');

then in the controller,

class UploadFilesController extends Controller
{
   private $uploadServiceInterface;

   public function __construct(UploadServiceInterface $uploadServiceInterface)
   {
      $this->uploadServiceInterface = $uploadServiceInterface;
   }

   public function uploadImage(Request $request)
   {
          $this->uploadServiceInterface->store();
   }

   public function uploadPdf()
   {
          $this->uploadServiceInterface->store();
   }
}

Now, the uploadServiceProvider,

class UploadServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->when(UploadFilesController::class)
            ->needs(UploadServiceInterface::class)
            ->give(ImagesUploadService::class);
    }

}

Now, I know "when" says that UploadFileController class with uploadService interface will give the imageUploadService but is it possible I make it more specific to function in uploadFileController class, like

$this->app->when(uploadFilesController::uploadImage())
->needs(UploadServiceInterface::class)
            ->give(ImagesUploadService::class);

then it takes to the imagesUploadService class same for pdf upload class.

0

There are 0 best solutions below