Using and registering service providers when coding to an interface

I’m wanting to register a NewsletterServiceProvider that must implement an interface, but I can’t figure out how to register and use the service provider properly with OctoberCMS.

I’ve got my interface defined, and I have a service provider class that implements it.

My understanding so far is that I create a NewsletterServiceProvider that returns an instance of the service provider for the service that I want to use in its register method and add it in to the providers array in config/app.php.

NewsletterInterface.php

interface NewsletterInterface
{
    public function subscribe($email);
}

MailChimpServiceProvider.php

class MailChimpServiceProvider implements NewsletterInterface
{
    public function subscribe($email)
    {
        //
    }
}

NewsletterServiceProvider.php

class NewsletterServiceProvider implements NewsletterInterface
{
    public function register()
    {
        $this->app->bind(
            NewsletterInterface::class,
            function($app) {
                return new  MailChimpServiceProvider();
            }
        );
    }
}

config/app.php

return [
    'providers' => array_merge(include(base_path('modules/system/providers.php')), [
        ....
        'Path\To\Plugin\Classes\Providers\NewsletterServiceProvider'
    ]),
]

Then I’m trying this when I want to use it…

$newsletter = new NewsletterInterface;
$newsletter->subscribe('me@company.tld');

But this doesn’t work and I’m not sure where I’m going wrong.

You can type hint the interface in a function or constructor and it will be resolved according to your binding.

e. g.

public function onNewSubscription(string $email, NewsletterInterface $newsletterService) {
    $newsletterService->subscribe($email);
}
1 Like

Hi Marco this works like a charm thank you very much.

I also found that I can do this too…

$newsletterService = App::make(NewsletterInterface::class);
$newsletterService->subscribe($email);

I think I was getting confused with the differences between the service container and what a service provider is.

1 Like