Programster's Blog

Tutorials focusing on Linux, programming, and open-source

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.

<?php

/*
 * Service provider for registering the php mailer wrapper.
 */


namespace Programster\PhpMailerWrapper;


class PhpMailerWrapperServiceProvider extends \Illuminate\Support\ServiceProvider
{
    public function register()
    {
        $this->app->singleton(PhpMailerWrapper::class, function() {
            return new PhpMailerWrapper(
                config('services.emailer.smtp_host'),
                config('services.emailer.aws_key'),
                config('services.emailer.aws_secret'),
                config('services.emailer.protocol'),
                config('services.emailer.from_email'),
                config('services.emailer.from_name')
            );
        });
    }
}

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:

    'emailer' => [
        'smtp_host' => 'email-smtp.eu-west-1.amazonaws.com',
        'aws_key' => env('AWS_KEY'),
        'aws_secret' => env('AWS_SECRET'),
        'protocol' => "tls",
        'from_email' => 'support@programster.org',
        'from_name' => 'support',
    ],

To add the service provider to Laravel, you need to edit the config/app.php file and add it like so:

...
        /*
         * Package Service Providers...
         */
        \Programster\PhpMailerWrapper\PhpMailerWrapperServiceProvider::class,
...

Using The Service

Now when you need to use the PhpMailerWrapper object, you do either of the following in your controller:

class MyController extends Controller
{
    public function main(\Programster\PhpMailerWrapper\PhpMailerWrapper $emailer)
    {
        $emailer->doSomething();

... or you can make use of the resolve method as shown here:

class MyController extends Controller
{
    public function main()
    {
        $emailer = resolve(\Programster\PhpMailerWrapper\PhpMailerWrapper::class);
        $emailer->doSomething();

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