拆分HTML和CSV的职责?

时间:2015-07-10 17:04:33

标签: php dry

我试图找出将HTML视图和CSV的责任分开以进行导出的最佳方法(相同的视图数据)。当它几乎做同样的事情时,我不想重复编写相同的CSV代码块。

下面的示例代码,首先从数据库中获取数据,然后将其处理为多维数组。您可以看到我使用了大量foreach来生成报告。我是否重复此操作以进行CSV导出?必须有一个DRY解决方案。

下面的示例代码,您将如何拆分CSV和HTML的职责?

function report($campaign, $agent, $startDate, $endDate) {

    $sql = "SELECT  count(*) as total, group_name, field, field, field, FROM table some ... inner joins table .. WHERE ... group by agent";

    $q = mysql_query($sql) or die(mysql_error());

    while($row = mysql_fetch_assoc($q)) {

        $report[ $row['group_name'] ][ $row['item'] ] ['total'] = 0;
        $report[ $row['group_name'] ][ $row['item'] ] ['total'] += $row['total'];
        $report[ $row['group_name'] ][ $row['item'] ] ['agent'][$row['agent']] = $row;

        if (!array_key_exists($row['agent'], $fieldsAgent)) {
            ..... 
        }
    }

    $html = "<table>";

    $html .= " <tr>";
    $html .= "   <td>Group</td>";
    $html .= "   <td>Item</td>";

    foreach($fieldsAgent as $agentCol => $agentTotal) {
        $html .= "<td>$agentCol</td>";
    }

    $html .= "  <td>Total</td>";
    $html .= "  </tr>";

    foreach ($report as $category => $items) {

        foreach($items as $itemName => $itemData) {

            $html .= "<tr>";
            $html .= " <td>" . $category . "</td>";
            $html .= " <td>" . $itemName . "</td>";

            foreach($fieldsAgent as $fieldAgentName => $totalAgentUser) {

                    $total = $itemData['agent'][ $fieldAgentName ][ 'total' ];
                    $html .= "<td>" . $total . "</td>";
            }

            $html .= " <td>" . $itemData['total'] . "</td>";
            $html .= "</tr>";
        } 
    }

    $html .= "</table>";

    echo $html;
}

1 个答案:

答案 0 :(得分:1)

我会创建一个名为tr_or_csv()

的函数
function tr_or_csv($data = array(), $mode = 'csv')
{
    $result = '';

    if(is_array($data) && $data)
    {
        $mode = (is_string($mode) ? (in_array(strtolower($mode, array('csv','tr'))) ? $mode : 'csv') : 'csv');

        if($mode === csv)
        {
            $handle = fopen('php://temp', 'r+');
            fputcsv($handle, $data, ',');
            rewind($handle);
            while (!feof($handle))
            {
                $result.= fread($handle, 8192);
            }
            fclose($handle);
        }
        else
        {
            $result = '<tr><td>';
            $result.= implode('</td><td>', $data);
            $result.= '</td></tr>';
        }
    }

    return $result;
}

function report($campaign, $agent, $startDate, $endDate, $mode)
{
    // MySQL stuff, etc...

    $html.= tr_or_csv(array('Group','Item','Total'), $mode);

    // More code
}

report('new_campaign', 'Bob', '2015-01-01', '2015-07-10', 'tr');