samedi 16 mai 2020

handle dynamic class name in factory pattern php

I have multiple provider for send email (elasticmail , mailgun , ...)

I have a class per provider:

class mailgun implement email {

     public function send() {
          // call send api
     }

}

class elasticmail implement email {

     public function send() {
          // call send api
     }

}

I create a factory class for make a instance of class

class emailFactory {
    public function make($name) {   
        if ($name = 'mailgun')
            return new mailgun();   

        return new elasticmail();
    }
}

The problem is that this method is not scalable for add new provider

for example Ymail added I Should add this name to Factory class:

class emailFactory {
    public function make($name) {   
        if ($name = 'mailgun') {
            return new mailgun();   
        } elseif ($name == 'Ymail') {
            return new Ymail();   
        }

        return new elasticmail();
    }
}

how to create a scalable factory class?

Aucun commentaire:

Enregistrer un commentaire