lundi 12 décembre 2016

PHP Factory methods

I was reading up on factory methods. Can someone explain why it is suggested that factory methods be located in a separate factory class?

I am pulling my example from here: http://ift.tt/2gE8xbt

class ETF {
  var $data;
  function ETF($data) {
    $this->data = $data;
  }
  function process() {}
  function getResult() {}
}

class VirtualCheck extends ETF {}
class WireTransfer extends ETF {}

class ETFFactory {
  function createETF($data) {
      switch ($data[‘etfType’]) {
      case ETF_VIRTUALCHECK : 
        return new VirtualCheck($data);
      case ETF_WIRETRANSFER :
        return new WireTransfer($data);
      default :
        return new ETF($data);
      }
  }
}

$data = $_POST;
$etf = ETFFactory::createETF($data);
$etf->process();

I would tend to instead write it like this:

class ETF {
    final public static function factory($data) {
        switch ($data[‘etfType’]) {
            case ETF_VIRTUALCHECK :
                return new VirtualCheck($data);
            case ETF_WIRETRANSFER :
                return new WireTransfer($data);
            default :
                return new ETF($data);
        }
    }

    var $data;
    function ETF($data) {
        $this->data = $data;
    }
    function process() {}
    function getResult() {}
}

class VirtualCheck extends ETF {}
class WireTransfer extends ETF {}

$data = $_POST;
$etf = ETF::factory($data);
$etf->process();

Am I wrong in doing this?

Aucun commentaire:

Enregistrer un commentaire