Laravel - Creating A Service Provider
Below is a very basic service provider that just registers a single service, the PhpMailerWrapper
, as a singleton to the Laravel service container.
If you need it to not be a singleton, you would just replace singleton
with bind
.
In this case the PhpMailerWrapper
is just a class that allows us to use PHPMailer to send emails with attachments easily.
The PhpMailerWrapper needs various configuration parameters in order to be created. You provide these to laravel by adding the following to /config/services.php
file:
To add the service provider to Laravel, you need to edit the config/app.php
file and add it like so:
Using The Service
Now when you need to use the PhpMailerWrapper
object, you do either of the following in your controller:
... or you can make use of the resolve
method as shown here:
Debugging
If you find yourself changing your service provider when debugging, remember to keep executing php artisan clear-compiled
to be sure the changes are applying.
References
First published: 5th October 2018