Service Providers

1 year ago by giacholari

Oftentimes, you need to inject behavior into a class. There are many ways to do so and the most common way is to pass a dependency through the constructor of the class. Then, you can manually new app the class or leverage a service provider that can do that for you automatically. Here is how that looks in Laravel. In the below example I have created an IPaymentService interface and a PaymentService class. The below code is within the App\Providers namespace.

public function boot()
    $this->app->singleton(IPaymentService::class, fn () =>  PaymentService(config('stripe.secret'));

Now wherever, I type-hint the IPaymentService, in return, I will get a single - shared (singleton) instance of PaymentService class. Remember to register the provider in the file.