Let’s says I have 3 items : a keyboard, a tshirt and a bottle of cola.
$keyboard = new Item("Keyboard");
echo $keyboard->getPrice(); // return 50;
$tshirt = new Item("Tshirt");
echo $tshirt->getPrice(); // return 20;
$cola = new Item("Cola");
echo $cola->getPrice(); // return 0 or 2 whether the bottle is empty or not.
What is the best practice to get the Price of the bottle of cola ?
I started by creating 2 classes :
Class Item {
$this->price;
function __construct($name) {
// ...
}
public function getPrice() {
return $this->price;
}
}
Class Bottle extends Item {
$this->empty;
function __construct($name) {
// get from database the value of $this->empty
}
public function getPrice() {
if($this->empty)
return 0;
else
return $this->price;
}
}
But now I’m wondering ; when I use : $cola = new Item("Cola");, I’m instantiating an Item object and not a Bottle object, because I don’t know yet if it’s a “normal” item or a bottle.
Should I instead instantiating a Bottle object and research for another logic in my application ? Or is there a way to “recreate” the item object and transforms it as a bottle ?
This is a perfect example of when to use the Factory Pattern.
For your code, you could do something like this.
You can use it like
$item = ItemFactory::getItem($yourvar)The Factory Pattern is useful when you have a lot of objects that have the same base (or parent) class, and you need to determine what class they are at runtime.