DOMDocument是一个更详细的XML接口,您可以使用simpleXML,这将减少锅炉板代码。
class XML {
public static function requestPresence(string $from, string $to, string $type = "subscribe")
{
$instance = new SimpleXMLElement("<presence />");
$instance["from"] = $from;
$instance["to"] = $to;
$instance["type"] = $type;
return $instance->asXML();
}
public static function setPriority(int $priority, string $from = null)
{
$instance = new SimpleXMLElement("<presence />");
if ($from) {
$instance["from"] = $from;
}
$instance->priority = $priority;
return $instance->asXML();
}
}
这假设它们是两个独立的需求,它们只是实用功能,而不必维护任何状态。
如果需要使用更多选项构建文档,则以下内容可能更有用…
class XML2 {
private $instance = null;
public function __construct() {
$this->instance = new SimpleXMLElement("<presence />");
}
public function requestPresence(string $from, string $to, string $type = "subscribe")
{
$this->instance["from"] = $from;
$this->instance["to"] = $to;
$this->instance["type"] = $type;
return $this;
}
public function setPriority(int $priority, string $from = null)
{
if ($from) {
$this->instance["from"] = $from;
}
$this->instance->priority = $priority;
return $this;
}
public function getXML() {
return $this->instance->asXML();
}
}
用…
echo (new XML2())->requestPresence("from", "to", "type")
->setPriority(1)
->getXML();
创造…
<?xml version="1.0"?>
<presence from="from" to="to" type="type"><priority>1</priority></presence>
使用domdocument或simplexml解决方案会比您的原始版本感觉更膨胀,但会提供一个比依赖字符串处理更可维护的更健壮的解决方案。