我的应用程序结构化的方式是,每个组件都以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代替。它更灵活,而且似乎表现更好(至少在我创建的粗略测试中)。