PHP Factory Pattern Step By Step Tutorial - Part 1: In Object Oriented Programming, we always create new object with new operator. And in some cases, we need call same class for different steps. We can create a factory to avoid always call same class. The factory pattern encapsulates the creation of objects.
This is simple example that we always create new object every function that need it.
<?php
class Vehicle{
function category($wheel = 0){
if($wheel == 2){
return "Motor";
}elseif($wheel == 4){
return "Car";
}
}
}
class Spec{
var $wheel = '';
function Spec($wheel){
$this->wheel = $wheel;
}
function name(){
$wheel = $this->wheel;
return Vehicle::category($wheel);
}
function brand(){
$wheel = $this->wheel;
$kind =& Vehicle::category($wheel);
if($kind == "Motor"){
return array('Harley','Honda');
}elseif($kind = "Car"){
return array('Nisan','Opel');
}
}
}
$kind = new Spec(2);
echo "Kind: ".$kind->name();
echo "<br>";
echo "Brand: ".implode(",",$kind->brand());
?>
This picture show how to implement factory pattern:

This is complete code after changing (implement factory pattern)
<?php
class Vehicle{
function category($wheel = 0){
if($wheel == 2){
return "Motor";
}elseif($wheel == 4){
return "Car";
}
}
}
class Spec{
var $wheel = '';
var $vc = '';
function Spec($wheel){
$this->wheel = $wheel;
$this->_getVehicle();
}
function &_getVehicle(){
$wheel = $this->wheel;
$this->vc =& Vehicle::category($wheel);
}
function name(){
return $this->vc;
}
function brand(){
if($this->vc == "Motor"){
return array('Harley','Honda');
}elseif($this->vc = "Car"){
return array('Nisan','Opel');
}
}
}
$kind = new Spec(2);
echo "Kind: ".$kind->name();
echo "<br>";
echo "Brand: ".implode(",",$kind->brand());
?>
In this practice, we create a factory within the object itself.