I came across the following code. It prints out HTML (using partial
function of ZF2), while also computing total, for all items, recursively.
function gen_items($parentId)
{
$total = 0;
$rows = $this->db->getData($parentId); //DB call!
foreach($rows as $row)
{
$id = $row['id']
$price = $row['price'];
echo $this->partial('item.phtml', array('price'=> $price));
$total += $price + $this->gen_items($id);
}
return $total;
}
first, I see this as a problem, because the name gen_items
makes sense for generating HTML code for line items, but it doesn't make sense for it to sum things.
One thought I have is to make a duplicate function that does all the same things, except one function will be for HTML generation, and one for summation.
Question
How can I make this decoupled? Is it possible to do it without creating essentially two functions that duplicate all the recursive DB calls?
More Details on DB
Database structure: table(id, price); id == -1
when there is no parent. Otherwise, id
points to parent id
.
Number of rows - say average about 5-10 parent items, each having 1 to 6 children total (some of it may be i.e. about 3 children with 1 sub-child of its own)