views:

47

answers:

2

Hi all,

I'm creating an interface for "PickupPoints", Each pickup point needs to be able to return all pickup points found and the pickup point details and maybe in the future more information. That's okay with the code below:

<?php

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


class PickupPoint1 implements iPickupPoint{
    ...
}

class PickupPoint2 implements iPickupPoint{
    ...
}

The problem is that I don't want to call the classes of PickupPoint1, PickupPoint2, .. them selves. I want a class like PickupPoint(PickupPointType) so I just want to give the type of pickup point and the types need to be PickupPoint1, PickupPOint2, ..

How can this be done? Is this even possible? Is this a best practice?

A: 

I would create 1 Pickup point function where you specify the pickup point number with an if statement inside.

Pickup Point ($pickuppointnum) {

  if ($pickuppointnum == 1){
    //Pickup Point information for Pickuppoint #1
  }
  elseif ($pickuppointnum ==2) {
    //Pickup Point information for Pickuppoint #2
  }
}
Bob Cavezza
That would become ugly when we have a 10 or more pickup points.
Skelton
+2  A: 

What you are describing is the Factory pattern, so yes, it's a best practice.

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

Your factory itself does not need to implement the interface. It could be a static class or even a function:

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");

The creation logic can be a lot more generic to avoid changing the factory every time you add a class to your application:

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());

This one is assuming you are creating your classes in files named "PickupPoint1.class.php" in the same directory that the factory is, and that the constructor in your classes need only one parameter.

I didn't test this code, so some bug might have slipped in.

Sebastián Grignoli
It is worth to notice, that the factory method (in your case `create()`) is named usually `factory()` *by convention*.
takeshin
I wasn´t aware of that. Is there any bibliography supporting this convention?
Sebastián Grignoli