Instantiating objects within result sets... best practices?
I'm developing an intranet site for reporting on data. I've developed
various classes for Customer, Order, Item, Invoice, etc that all relate to
each other in one way or another. Each class constructor queries a MySQL
database (multiple queries) and populates the properties accordingly.
Currently, to try and keep code convenient and consistent, I'm relying a
lot on instantiating classes in my reporting. The problem is, each class
constructor may have a bunch of MySQL queries within them, pulling or
calculating relevant properties from various sources. This causes a
performance hit because of all the queries within loops. It's usable, and
I wont ever have a ton of users at once.. but it could be much faster.
For example, let's say I'm listing the last 50 orders from a customer. The
way I'm doing it now, I'll typically write a simple query that returns the
50 order ID's alone for that customer. Then while looping through the
results, I'll instantiate a new order for each results. Sometimes I may
even go one level deeper and then instantiate a new object for each item
within the order.
Some pseudocode to give the idea....
$result = mysql_query("SELECT DISTINCT id FROM orders WHERE customer =
1234 LIMIT 50");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$order = new Order($row['id']); // more MySQL queries happen in
constructor
// All of my properties are pre-calculated and formatted
// properly within the class, preventing me from having to redo it
manually
// any time I perform queries on orders
echo $order->number;
echo $order->date;
echo $order->total;
foreach($order->items as $oitem) {
$item = new Item($oitem); // even more MySQL queries happen here
echo $item->number;
echo $item->description;
}
}
I may only use a few of the object properties in a summary row, but when I
drill down and view an order in more detail, the Order class has all the
properties I need ready to go, nice and tidy.
What's the best way this is typically handled? For my summary queries,
should I try to avoid instantiating classes and get everything in one
query that's separate from the class? I'm worried that will cause me to
have to manually do a lot of background work I typically do within the
class every single time I do a result set query. I'd rather make a change
in one spot and have it reflect on all the pages that I'm querying the
effected classes/properties.
What are other ways to handle this appropriately?
No comments:
Post a Comment