我有几个想法可以考虑。
#1
使用模板引擎,像Smarty,很可能会令这一点更容易维护。它至少会摆脱你的PHP代码中的XML。
例如,您可以创建的XML模板段,您发布的评论:
<?xml version="1.0" encoding="UTF-8" ?>
{foreach from=$graphs item=graph}
<graph caption="{$graph.caption}" showNames="{$graph.show_names}" decimalPrecision="{$graph.decimal_precision}" bgcolor="{$graph.bg_color}">
{foreach from=$graph.set item=set}
<set name="{$set.name}" value="{$set.value}"/>
{/foreach}
</graph>
{/foreach}
而且从PHP称其为
<?php
$address = $_SERVER['PHP_SELF'];
$smart = new Smarty();
$graphs = array();
if ($address == 'webService.php/fcf/last5pricechanges/')
{
$graph_result = mysql_query("SELECT caption, show_names, decimal_precision, bg_color
FROM graph WHERE something='something else'");
while($graph_row = mysql_fetch_assoc($graph_result))
{
$graph_row;
$set_result = mysql_query("SELECT name, value FROM set WHERE graph_id = {$graph_row['id']}");
while($set_row = mysql_fetch_assoc($set_result))
{
$graph_row['sets'][] = $set_row;
}
$graphs[] = $graph_row;
}
}
$smarty->assign('graphs', $graphs);
$smarty->display('graph_template.tpl');
?>
#2
您可以创建对象帮助您管理代码。例如,像以前一样产生相同的XML输出,你可以这样做:
<?php
class Graph
{
protected $caption;
protected $show_names;
protected $decimal_precision;
protected $bg_color;
protected $sets;
public function __construct($graph_id)
{
$graph_result = mysql_query("SELECT caption, show_names, decimal_precision_bg_color
FROM graph WHERE something='something else'");
while($graph_row = mysql_fetch_assoc($graph_result))
{
list($this->caption, $this->show_names, $this->decimal_precision, $this->bg_color) = $graph_result;
$set_result = mysql_query("SELECT name, value FROM set WHERE graph_id = {$graph_row['id']}");
while($set_row = mysql_fetch_assoc($set_result))
{
$this->sets[] = $set_row;
}
}
}
public function fetch_xml()
{
$output = '<?' . 'xml version="1.0" encoding="UTF-8" ?' . '>';
$output .= "<graph caption=\"{$this->caption}\" showNames=\"{$this->show_names}\" decimalPrecision=\"{$this->decimal_precision}\" bgcolor=\"{$this->bg_color}\">\n";
foreach($this->sets as $set)
{
$output .= "<set name=\"{$set->name}\" value=\"{$set->value}\"/>\n";
}
$output .= "</graph>";
return $output;
}
}
?>
,并调用它在你的主代码,如:
<?php
$address = $_SERVER['PHP_SELF'];
if ($address == 'webService.php/fcf/last5pricechanges/')
{
$graph = new Graph(1);
echo $graph->fetch_xml();
}
?>
#3
你可以尝试使用的东西像SimpleXML,但我怀疑这将有助于很大程度的可维护性,因为它将与回声方法一样冗长。
和#4
...不,我全力以赴:-) 希望有所帮助。
感谢您的回答。 Smarty似乎是要走的路,因为我可以为每个图创建模板,使修改变得更容易。 – CJD 2009-12-06 16:15:17