Back to Blog
Dotkernel API

How to implement MailChimp in Dotkernel API

This article will walk you through the process of implementing MailChimp into your instance of Dotkernel API using drewm/mailchimp-api.

Step 1: Add the library to your application using the following command:

composer require drewm/mailchimp-api

Step 2: Create configuration file config/autoload/mailchimp.global.php and paste the following content inside of it:

<?php

declare(strict_types=1);

return
];

Step 3: Create factory src/App/src/MailChimp/Factory/MailChimpFactory.php which will return an instance of DrewM\MailChimp. Paste the following content inside this file:

<?php

declare(strict_types=1);

namespace Api\App\MailChimp\Factory;

use DrewM\MailChimp\MailChimp;
use Psr\Container\ContainerInterface;

/**
 * Class MailChimpFactory
 * @package Api\App\MailChimp\Factory
 */
class MailChimpFactory
{
    /**
     * @param ContainerInterface $container
     * @return MailChimp
     * @throws \Exception
     */
    public function __invoke(ContainerInterface $container) : MailChimp
    {
        $config = $container->get('config')['mailChimp'] ?? [];

        return new MailChimp($config['apiKey'] ?? '');
    }
}

Step 4: Let your application use this factory by adding it to the main ConfigProvider. To do this, open file src/App/src/ConfigProvider.php and locate the method called getDependencies(). Inside this method, locate the key factories which points to an array. Inside this array add the following line:

MailChimp::class => MailChimpFactory::class,

Make sure you add the corresponding uses:

use Api\App\MailChimp\Factory\MailChimpFactory;
use DrewM\MailChimp\MailChimp;

After this, you can start using the library by @Injecting MailChimp::class where it's needed.

Frequently Asked Questions

Which library does this tutorial use to add MailChimp to Dotkernel API? +

The tutorial uses drewm/mailchimp-api, installed with the command composer require drewm/mailchimp-api.

Where do you place the MailChimp configuration file? +

In config/autoload/mailchimp.global.php, a new configuration file created as part of Step 2.

What does the MailChimpFactory class do? +

It's a factory, created at src/App/src/MailChimp/Factory/MailChimpFactory.php, that reads the config from the container and returns an instance of DrewM\MailChimp\MailChimp.

Where do you register the MailChimp factory so the application can use it? +

In src/App/src/ConfigProvider.php, inside the getDependencies() method's factories array, by mapping MailChimp::class to MailChimpFactory::class, plus adding the corresponding use statements for MailChimp and MailChimpFactory.

How do you use MailChimp once it's wired up? +

By injecting MailChimp::class wherever it's needed, using @Inject.