2

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)

Dennis
  • 7,907
  • 11
  • 65
  • 115
  • perhaps to add -- do I make it decoupled in the first place. Should I? – Dennis Apr 17 '15 at 17:04
  • Looks like you're querying for the information in the rows to begin with. Why not include in that query some SQL to get the sum of the prices as well? – Muhammad Abdul-Rahim Apr 17 '15 at 17:06
  • may need more info .... I am not too familiar with constructing SQL queries that recursively compute sums, pulling row data recursively.... Plus I will still need individual line item data as well. – Dennis Apr 17 '15 at 17:08
  • 1
    There's a question on that topic if you'd like to do some research. I fear it may be a little far from what would be best in this situation, but please let me know: http://stackoverflow.com/questions/16545467/finding-recursive-sum-in-sql-statement – Muhammad Abdul-Rahim Apr 17 '15 at 17:11
  • I can also, instead of decoupling this, call this function `sum_item_prices`, with a *side-effect* of printing line items in HTML, and leave this as-is, documenting side-effect. – Dennis Apr 17 '15 at 17:18
  • @mari, thanks that's a cool feature to know. I'll have to look into it. I'm on MySQL – Dennis Apr 17 '15 at 17:23

1 Answers1

0

I am pursuing a solution that:

  • reads DB recursively
  • accumulates rows read from DB in a PHP structure
  • provides that structure back to the caller in a nice array

Caller than

  • runs iterative algo to print HTML with values from array, and, separately
  • sums pricing info.

Voila!

--- code possibly to be added after it is is written- -
(it's basically same but instead of $total I accumulate $childRows)

Dennis
  • 7,907
  • 11
  • 65
  • 115