You can’t work with a modern framework without tripping over the concept of dependency injection, this paradigm offers a clean, organized, and maintainable way to integrate reusable code as service.
To give an illustration of what I mean, let’s look at the case of creating a newsletter using Mailchimp which may be replaced by other providers down the road.
Install the Mailchimp package:
“spatie/laravel-newsletter” simplifies Mailchimp integration in Laravel. This command installs it using Composer:
|
|
Configure the Mailchimp API credentials:
We use config and env instead of hardcoding variables.
|
|
In serveics.php file in the config directory
|
|
Create the contract
Define an interface in a Services directory, this will force us to have one method so far subscribe.
The first parameter of the ‘subscribe()’ method is the member’s email address, while the second and final parameter is the list id.
|
|
Note This interface doesn’t expose any details about how exactly how the subscribe method works.
Contract implementation
A Mailchimp corresponding implementation will be something like the following
|
|
Register the Newsletter service in laravel ServiceProvider
In the public function register(): void of AppServiceProvider.php
|
|
Using the service
Now, in the call site, which is typically a controller, we use the type hint rather than the implementation class.
|
|