php - Assistance with factory pattern implementation -


i’ve tagged question php, it’s more question on design patterns, namely factory pattern; php programming language i’m using.

i’m building estate agents’ (“real estate” american cousins) website. have property class, other classes extend this, i.e. lettingproperty, commercialproperty has fields specific type of property.

in controller want display particular property. easy pass property id parameter. approach create factory class returns property instance of relevant class. example, if property id of 1 letting property, return instance of lettingproperty. if it’s standard “for sale” property, instance of property.

how can go this? created propertyfactory class , implemented method called buildfromid(), having trouble on creating elegant solution to:

  • find relevant record in properties database table
  • do left joins (i.e. if it’s letting property left join relevant data letting_properties (foreign key: property_id)
  • return resultant data, instance of corresponding class

is factory approach correct design pattern scenario? , if so, how go above?

if can produce query variably flattens the tree using left joins can on php side create object model. of course want fill out implementation more on property types them useful.

 class property {     public function setpropertyvaluesfromarray($array){         foreach($array $k=>$v){             $this->$k = $v;         }     }  }   class commercialproperty extends property {}  class lettingproperty extends property {}   class propertyfactory {     protected $db;      public function __construct(dbconnection $db){         $this->db = $db;     }     public function getpropertybyid($id){         $result = $this->db->fetchrow($querytogetpropertybyid);         return $this->getpropertyfromarray($result);     }     public function getpropertyfromarray($result){         switch($result["property_type"]){             case "residential":                 $p = new property();                 break;             case "commericial":                 $p = new commercialproperty();                 break;             case "letting":                 $p = new lettingproperty();                 break;             default:                 throw new exception("unknown property type ".$result["property_type"]);                 break;         }         $p->setpropertyvaluefromarray($result);         return $p;     }  } 

Comments