Emilio Astarita wrote: > Hi people, > > I want a class that allows create objects that get the information > consulting the DB. So, I am thinking to do something like this: > > class element { > public __construct($id,$type = 'id') { > switch($type) { > case 'id': > $where = sprintf(" id = %d ",$id); > break; > case 'name': > $where = sprintf(" name = %s ",escape($id)); > break; > //... > // get the row and call setName($row['name'])... > } > } > } > > This works fine, but also I want a good way (efficient) of getting a > collection of these objects. I can't figure a convenient way. A static > function its a good posibility? I have some ideas but they imply public > setters of the class `element'. > > Thanks for any help. > A static method should still be able to set values of private members. I do something like: class Element { private $id; private $name; public __construct() { // Do general construction tasks... } public static bulkLoad($id,$type='id') { $ret = Array(); $sql = 'SELECT id,name FROM Table '; switch ($type) { case 'id': $sql .= 'WHERE id ILIKE $1'; // Use ILIKE to allow for wildcards break; case 'name': $sql .= 'WHERE ILIKE $1'; // Use ILIKE to allow for wildcards break; //... } $params = Array($id); // I use postgreSQL parameterised queries a lot - saves lots of quoting etc. // Note: NO ERROR CHECKING in this example... $data = pg_fetch_all(pg_query_params($sql,$params)); foreach ($data as $row) { $elem = new Element(); // No-args constructor $elem->id = $row['id']; $elem->name = $row['name']; $ret[$id] = $elem; } return $ret; } } Then you get an array of elements which match the (possibly wild-carded) condition, indexed by the element Id (useful for making HTML <select> lists, for example). In fact, I have a base class which implements this by class introspection - filling the properties of objects which extend it by mapping them to the database fields... -- Peter Ford phone: 01580 893333 Developer fax: 01580 893399 Justcroft International Ltd., Staplehurst, Kent -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php