PHP Factory Pattern Step By Step Tutorial - Part 4: In this post, we will look advantage use external factory class that ever we talk at here. We can add more 'behind process'.
We still use our practice from external factory class. But we add a behind process like this:
At this practice, we will check number of wheel. If user add not 2 or 4, we will return 2 as default.
<?
class Vehicle{
function category($wheel = 0){
if($wheel == 2){
return "Motor";
}elseif($wheel == 4){
return "Car";
}
}
}
class GetVehicle{
function validWheel(){
$arr = array(2,4);
return $arr;
}
function get($wheel){
if(in_array($wheel, GetVehicle::validWheel())){
return Vehicle::category($wheel);
}else{
// make default 2
return Vehicle::category(2);
}
}
}
class Spec{
var $wheel = '';
var $vc = '';
function Spec($wheel){
$this->wheel = $wheel;
$this->vc =& GetVehicle::get($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(4);
echo "Kind: ".$kind->name();
echo "<br>";
echo "Brand: ".implode(",",$kind->brand());
?>