在PHP中创建一个接口,它可以指定一个类型来确定要使用的类

时间:2010-08-21 05:46:10

标签: php oop design-patterns interface

我正在为“PickupPoints”创建一个界面,每个拾取点都需要能够返回找到的所有拾取点和拾取点详细信息,并可能在将来提供更多信息。这可以使用下面的代码:

<?php

interface iPickupPoint
{
    public function getPickupPoints($countryCode, $postalCode, $city);
    public function getPickupPointDetails($pickupPointId);
}


class PickupPoint1 implements iPickupPoint{
    ...
}

class PickupPoint2 implements iPickupPoint{
    ...
}

问题在于我不想调用PickupPoint1,PickupPoint2,它们自己的类。 我想要一个像PickupPoint(PickupPointType)这样的类,所以我只想给出拾取点类型,类型需要是PickupPoint1,PickupPOint2,..

如何做到这一点?这甚至可能吗?这是最佳做法吗?

2 个答案:

答案 0 :(得分:4)

您所描述的是工厂模式,所以是的,这是最佳实践。

http://www.devshed.com/c/a/PHP/Design-Patterns-in-PHP-Factory-Method-and-Abstract-Factory/

您的工厂本身不需要实现该接口。它可以是静态类,甚至是函数:

class PickupPointFactory{
  public static function create($type){
    /* your creation logic here */
    switch ($type) {
      case "PickupPoint1" : 
        $obj = new PickupPoint1(); 
      break;
      case "PickupPoint2" :
        $obj = new PickupPoint2();  
      break;
    }
    return $obj;
  }
}

$newPoint = PickupPointFactory::create("PickupPoint2");

创建逻辑可以更通用,以避免每次向应用程序添加类时更改工厂:

class PickupPointFactory{
  public static function create($type, $options){
    /* your creation logic here */
    if(file_exists(dirname(__FILE__).'/'.$type.'.class.php')) {
      require_once(dirname(__FILE__).'/'.$type.'.class.php');
      $obj = new $type($options);
      return $obj;
    } else {
      throw new Exception('Unknown PickupPoint type: '.$type);
    }
  }
}

$newPoint = PickupPointFactory::create("PickupPoint2", array());

这假设您在工厂所在的同一目录中创建名为“PickupPoint1.class.php”的文件中的类,并且您的类中的构造函数只需要一个参数。

我没有测试这段代码,因此可能会出现一些错误。

答案 1 :(得分:-1)

我会创建1个拾取点功能,您可以在其中指定带有if语句的拾取点编号。

Pickup Point ($pickuppointnum) {

  if ($pickuppointnum == 1){
    //Pickup Point information for Pickuppoint #1
  }
  elseif ($pickuppointnum ==2) {
    //Pickup Point information for Pickuppoint #2
  }
}