Skip to content

Instantly share code, notes, and snippets.

@exileed
Forked from tkouleris/Factory.php
Created December 1, 2016 04:16
Show Gist options
  • Save exileed/6e2f72776d1774126c806b0c88e3de89 to your computer and use it in GitHub Desktop.
Save exileed/6e2f72776d1774126c806b0c88e3de89 to your computer and use it in GitHub Desktop.
Factory Design Pattern example
<?php
/*
*
* Factory Design Pattern
* -----------------------
* Wiki: In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating
* objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory
* method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived
* classes—rather than by calling a constructor.
*
*/
interface Cook{
public function cookMeal($time);
}
class CookPizza implements Cook{
public function cookMeal($time = 1){
echo "Cooking pizza for ". $time . " hour and its ready.\r\n";
}
}
class CookPasta implements Cook{
public function cookMeal($time = 1){
echo "Cooking pasta for ". $time . " hour and its ready.\r\n";
}
}
class CookBeans implements Cook{
public function cookMeal($time = 1){
echo "Cooking beans for ". $time . " hour and its ready.\r\n";
}
}
// Our Cooking Factory
class CookingFactory{
public function mealChoice( $meal = null ){
switch ($meal) {
case null:
echo "Nothing to cook.\r\n";
break;
case "pizza":
return new CookPizza();
case "pasta":
return new CookPasta();
case "beans":
return new CookBeans();
default:
echo "I cannot cook this.\r\n";
}
}
}
//Client Code
//Get a factory instance
$foodFactory = new CookingFactory();
//Use the instance to get the instance you want
$nothing = $foodFactory->mealChoice();
$pasta = $foodFactory->mealChoice("pasta");
$beans = $foodFactory->mealChoice("beans");
$notCooking = $foodFactory->mealChoice("Cake");
$pizza = $foodFactory->mealChoice("pizza");
//Start Cooking
$pasta->cookMeal();
$beans->cookMeal();
$pizza->cookMeal();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment