I came up with a solution (in PHP) to a problem and am wondering if it is a named Design Pattern, and if it is good practice.
I have a collection class and an item class. The collection class is the only one allowed to set the item class's protected data, besides the class itself.
I did that by giving the item
class a method that takes the collection
object as an argument. The item
object then sets its data with the collection
objects.
That way, we can say:
$item_coll = new collection();
$item_coll->load($criterion1, $criterion2);
And now there is a collection of `item` objects with all their data set.
class item {
protected $prop1;
protected $prop2;
public function setData(collection $coll, $id) {
$data = $coll->getData($id);
foreach($data as $key=>$value) {
$this->$key = $value
}
return $this;
}
}
class collection {
protected $data = array();
public function getData($id) {
if(array_key_exists($id,$this->data) ) {
return $this->data[$id];
} else return array();
}
public function load(someClass $obj1, someClass2 $obj2) { // arguments not relevant here, they determine the contents of the collection
// based on arguments, data is loaded from database into $this->data;
foreach($rows as $row) { // database data
$this->data[$id] = $row;
$obj = $this->collection[$id] = new item();
$obj->setData($this,$id); // collection object passes itself into item object
}
}
}
Aucun commentaire:
Enregistrer un commentaire