lundi 19 novembre 2018

design pattern for switching email providers in the code

We need to send emails in our php app (who doesn't). Initially when our app was in infancy, we used simply linux sendmail. A bit moving forward we switched to our own SMTP server. That means code change in every file that has email related function. A year later we shifted to AWS and had to change the code again to start using AWS email service. Now we moved to Google cloud and again email code is changed to use some third party provider.

Configuration of email, is spread all over the places and changing one provider means hundreds of files need to be updated and if you miss one, clients may not be able to receive email for one part but can get emails for other.

I just took a step back and realized that we are changing code that makes no sense to change only because our email provider is changed.

But for the life of me I am unable to figure out what would be a way out of this mess.

All I need to do is to remove emailing from my code and refactor it in such a way that my app code can function independent of the mail service provider.

Her is my take on this

class EmailGateway()
{
  private $emailer;
  public function __construct($someEmailProvider)
  {
     $this->emailer = $someEmailProvider;
  }

  public function send($from, $to, $subject, $bodyText, $bodyHtml="")
  {

    this->emailer->send($from, $to, $subject, $bodyText, $bodyHtml="");
  }
}

And then in my code all I need is to call it like

# Gmail?
$mailGateway = new EmailGateway(new GmailEmailer("username", "password"));

# local?
$mailGateway = new EmailGateway(new SendMailer());

# SMTP?
$mailGateway = new EmailGateway(new MyMailServerMailer("192.168.0.3", "no_user", "secret_password"));

Am I doing it the right way? Is it a proper strategy pattern at all? Should I even care about what pattern it is as long as it can solve my problem?

Is there a better way to pull myself out of this ever increasing mess?

Aucun commentaire:

Enregistrer un commentaire