我使用 TDD (SimpleTest) 完成了我的第一堂课。它工作得很好。此类解析 XML 配置文件并将其作为数组返回。我该如何改进它(性能,任何提示)?班级责任呢?也许 XMLtoArray 应该移到另一个类,我不知道......
<?php
class Configuration
{
private $domdocument_object;
private $domxpath_object;
public function __construct($filename) {
$this->loadXML($filename);
$this->domxpath_object = new DOMXPath($this->domdocument_object);
}
private function loadXML($filename)
{
if (!file_exists($filename))
{
throw new ConfigurationException('Configuration file not found');
}
$this->domdocument_object = $domdocument_object = new DOMDocument();
$this->domdocument_object->preserveWhiteSpace = false;
if (!$this->domdocument_object->load($filename))
{
throw new ConfigurationException('Malformed configuration file');
}
}
public function get($path = '/*') {
$configuration = array();
$domnodelist_object = $this->domxpath_object->query($path);
$configuration = $this->XMLToArray($domnodelist_object);
/**
* Get a configuration entry as string or array
*
* For example:
* $xml = '<foo><bar>baz</bar></foo>'
* $path = '/foo/bar/'
* return just baz, as string instead of an array('baz');
*
* Another example:
* $xml = '<foo><bar>baz</bar><lorem>ipsum</lorem></foo>';
* $path = '/foo'
* return just array('bar' => 'baz', 'lorem' => ipsum);
* instead of array('foo' => array('bar' => 'baz', 'lorem' => ipsum));
*/
while (!is_string($configuration) && count($configuration) == 1)
{
$configuration_values = array_values($configuration);
$configuration = $configuration_values[0];
}
if (empty($configuration))
{
$configuration = null;
}
return $configuration;
}
public function XMLToArray(DOMNodeList $domnodelist_object) {
$configuration = array();
foreach ($domnodelist_object as $element)
{
if ($element->nodeType == XML_DOCUMENT_NODE)
{
if ($element->hasChildNodes())
{
$configuration = $this->XMLToArray($element->childNodes);
}
}
else if ($element->nodeType == XML_ELEMENT_NODE)
{
if (!$element->hasChildNodes())
{
$configuration[$element->nodeName] = null;
}
else if (
$element->firstChild->nodeType == XML_TEXT_NODE ||
$element->firstChild->nodeType == XML_CDATA_SECTION_NODE
)
{
$configuration[$element->nodeName] = $element->nodeValue;
}
else if ($element->firstChild->nodeType == XML_ELEMENT_NODE)
{
$configuration[$element->nodeName] = $this->XMLToArray($element->childNodes);
}
}
}
return $configuration;
}
}
?>
此类忽略 XML 属性。谢谢你。