2009-11-29 73 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獲取一個作家作爲輸入,並返回它作爲輸出