dimanche 11 mars 2018

Mail service class design (PHP)

I'm currently creating a mailer class nested into the service layer. Let's call it MailService.

MailService has a single dependency: a transport object.

The point is, this transport object can be of 3 different types, according to the environment (dev, prod, unit tests).

So, not a big deal! However, I'm looking for the cleanest way to design it. Here's what I thought to do, please tell me if this could be done otherwise according to you:

  1. Use the factory design pattern to create the transport instance needed, according to the environment the app is running on.
  2. Instantiate the mailer service by passing the transport as a parameter to its constructor.

The code could look like so:

class ApplicationEnv {
  const DEVELOPMENT = 0;
  const PRODUCTION = 1;
  const TESTING = 2;
}

class TransportFactory {

  public static function create() {
    switch (APPLICATION_ENV) {
      case ApplicationEnv::DEVELOPMENT: return new SomeTransport1();
      case ApplicationEnv::PRODUCTION: return new SomeTransport2();
      case ApplicationEnv::TESTING: return new SomeTransport3();
    }
  }

}

class MailService {

  public function __construct($oTransport) {
    // ...
  }

  public function send() {
    // ...
  }

}

$oTransport = TransportFactory::create();
$oMailService = new MailService($oTransport);
$oMailService->send();

Waiting for your comments...

Thank you!

Aucun commentaire:

Enregistrer un commentaire