If I'm creating an object that gets stored in a MySQL DB, it might get its properties like this (not complete code):
class thing {
var $someval;
function thing($id = 0) {
if ($id > 0) {
$query = "Select someval from table where id = '$id'";
$result = mysql_query($query);
$data = mysql_fetch_array($result);
$someval = $data[0];
}
}
}
Now that's a nice clean OO-way of doing that kind of thing. However, say I have an array of 10,000 of these things, it's horribly inefficient, generating 10,000 separate batabase queries when it could be done in one. Some kind of Factory pattern would seem appropriate, but it seems I would need a method that allowed the direct setting of all instance vars in the class, e.g.
function setvals($someval = '') {
$this->someval = $someval;
}
and my factory would look something like:
$query = "Select someval from table where someotherval > 5"; //A query that returns more than one result
$result = mysql_query($query);
$things = array(); //objects accumulate in here
while($data = mysql_fetch_array($result)) {
$thing = new thing;
$thing->setvals($data[0]);
$things[] = $thing;
}
Notice that we're not supplying the ID to the thing constructor, thus making an "empty" object into which we manually insert data.
Although this is clearly more efficient, it means that you do need this distinctly ugly setvals method (which would be extremely ugly in an object with 50 properties). It would be much better implemented as a polymorphic constructor on the thing object, but I don't think PHP allows that. It also means that the factory code needs to know intimate details of the object's internals, which just doesn't seem right.
Similarly, it's OO friendly if each instantiated object has a connection to the DB to talk to, but given 10,000 of these object, that represents 10,000 database connections, which doesn't seem like a good idea. How can I share a connection amongst multiple objects while keeping it OO clean? Would it be a good idea to make the connection variable static?
Can anyone please comment on this approach?