2009-11-29 36 views
1

我的应用程序结构化的方式是,每个组件都以XML形式生成输出并返回一个XmlWriter对象。在将最终输出呈现给页面之前,我组合所有XML并对该对象执行XSL转换。下面是应用程序结构的简化代码示例。组合XmlWriter对象?

将此类XmlWriter对象组合起来是否合理?有没有更好的方式来构建我的应用程序?最佳解决方案是我不必将单个XmlWriter实例作为参数传递给每个组件。

function page1Xml() { 
$content = new XmlWriter(); 
$content->openMemory(); 
$content->startElement('content'); 
$content->text('Sample content'); 
$content->endElement(); 
return $content; 
} 

function generateSiteMap() { 
$sitemap = new XmlWriter(); 
$sitemap->openMemory(); 
$sitemap->startElement('sitemap'); 
$sitemap->startElement('page'); 
$sitemap->writeAttribute('href', 'page1.php'); 
$sitemap->text('Page 1'); 
$sitemap->endElement(); 
$sitemap->endElement(); 
return $sitemap; 
} 

function output($content) 
{ 
$doc = new XmlWriter(); 
$doc->openMemory(); 
$doc->writePi('xml-stylesheet', 'type="text/xsl" href="template.xsl"'); 
$doc->startElement('document'); 

$doc->writeRaw(generateSiteMap()->outputMemory()); 
$doc->writeRaw($content->outputMemory()); 

$doc->endElement(); 
$doc->endDocument(); 

$output = xslTransform($doc); 
return $output; 
} 

$content = page1Xml(); 
echo output($content); 

更新:
我可以完全放弃的XmlWriter和使用的DomDocument代替。它更灵活,而且似乎表现更好(至少在我创建的粗略测试中)。

回答

0

线对于我想要做的事非常有效。我决定最好的方法是使用DOMDocument。不同之处在于:DOMDocument在输出之前不会生成任何XML,而XmlWriter基本上是一个StringBuilder,不够灵活。

2

在这个架构中我宁愿通过作家输出的集合,沿着我从未见过任何人相结合的XmlWriter对象这样的,我不认为这是

function output($ary) { 
    ..... 
    foreach($ary as $w) $doc->writeRaw($w->outputMemory()); 
    ..... 
} 

output(array(page1(), siteMap(), whateverElse())) 
0

我将有page1Xml和generateSiteMap获取一个作家作为输入,并返回它作为输出