请检查我创建的以下类以构建少量XML框架.
class CommandBuilder
{
public function __construct()
{
//
}
public function login($username, $password)
{
$frame = $this->frame();
$command = $frame->addChild('command');
$login = $command->addChild('login');
$login->addChild('username', $username);
$login->addChild('password', $password);
$command->addChild('authKey', 'authkey');
return $frame->asXML();
}
public function info($id)
{
$frame = $this->frame();
$command = $frame->addChild('command');
$login = $command->addChild('product');
$login->addChild('id', $id);
$command->addChild('authKey', 'authkey');
return $frame->asXML();
}
protected function frame()
{
return new SimpleXMLElement(
'<app/>'
);
}
}
Run Code Online (Sandbox Code Playgroud)
什么是避免重复$frame->addChild('command')和$command->addChild('authKey', 'authkey')不改变元素顺序的最佳方法?
请帮助改进代码.谢谢
尽管您拥有的代码可以简化,但也存在复杂性。我这样做的方式是将框架的构建转移到方法中frame。其他每个例程都会构建<command>节点的基础并将其传递下去,然后框架方法添加 authkey 位。这段代码会做同样的事情 - 但它必须在所有帧上完成......
class CommandBuilder
{
public function __construct()
{
//
}
public function login($username, $password)
{
$command = new SimpleXMLElement('<command />');
$login = $command->addChild('login');
$login->addChild('username', $username);
$login->addChild('password', $password);
return $this->frame($command);
}
public function info($id)
{
$command = new SimpleXMLElement('<command />');
$login = $command->addChild('product');
$login->addChild('id', $id);
return $this->frame($command);
}
protected function frame( $node ) {
$node->addChild('authKey', 'authkey');
$xml = new DOMDocument();
$xml->loadXML('<app/>');
// Convert SimpleXML to DOMDocument
$fromDom = dom_import_simplexml($node);
// Add in the $node passed in to the frame
$xml->documentElement->appendChild($xml->importNode($fromDom, true));
return $xml->saveXML();
}
}
Run Code Online (Sandbox Code Playgroud)