dimanche 4 octobre 2015

PHP Multiton Factory Pattern for Extensibility and Different Types of Same Object

My goal is to create a closed php class Registrar that can return a collection of children based on the children's supported tlds (top level domains). I think I might be mixing like 2 or 3 different object oriented design patterns here. Can you help me sort out which design pattern(s) are appropriate here?

This is the base class. You would call get_registrars on it and pass in a tld like 'com' and get an array of registrars which support the 'com' tld.

class Registrar {
  public static $tld_registrars = array();
  public static $registrars = array();

  public static function add_registrar($class) {
    array_push(self::$registrars, $class);
  }

  public static function get_registrars($tld) {
    var_dump(self::$registrars);
    if( ! isset($tld_registrars[$tld]) ) { 
      $tld_registrars[$tld] = array();

      foreach (self::$registrars as $registrar) {
        if( in_array($tld, $registrar->supported_tlds) ) {
          array_push($tld_registrars[$tld], $registrar);
        }
      }

    }

    return $tld_registrars[$tld];
  }
}

This is a child class. You could add a new to the application just by defining it's name, short_name, and supported tlds and then adding it to the parent Registrar class.

class Godaddy_Registrar extends Registrar {

  public $supported_tlds = array('com', 'org', 'net', 'info');
  public $name = 'Godaddy';
  public $short_name = 'GD';

  parent::add_registrar(new self);



}

...But this code doesn't work because parent::add_registrar can't be called when the class loads like this.

I've used a pattern like this in ruby but not in PHP. Can this be done in PHP? Is there a better way to achieve this type of functionality than the way I'm trying to do it?

Aucun commentaire:

Enregistrer un commentaire