In software and web development, it’s always important to write code that is maintainable and extendable. This post is written for Laravel developers who have an understanding of how interfaces work and how to use them to decouple your code.
So, to avoid this issue, instead of trying to instantiate a class in the controller method, we can use the bridge pattern to bind and resolve an interface instead. Let’s start by creating a new ExchangeRatesService interface: We can now update our ExchangeRatesApiIO class to implement this interface: Now that we’ve done that, we can update our controller method to inject the interface rather than the class: Of course, we can’t instantiate an interface; we want to instantiate the ExchangeRatesApiIO class.
Let’s create a new service provider using the Artisan command: We’ll then need to remember to register this service provider inside the app/config.php like below: Now, we can add our code to the service provider to bind the interfaces and class: Now that we’ve done all of this, when we dependency inject the ExchangeRatesService interface in our controller method, we'll receive an ExchangeRatesApiIO class that we can use.