I want to create xml messages for sharing via webservice. These messages must be created from a pool of reusable items. So I created different classes. Class "factory", which returns a class of messages. An element class that consists of reusable parts and message classes that are drawings for the required xml messages.
My code provides the expected result, but I'm looking for best practice. Especially a way to get rid of rewriting the same save () and * __ construct * methods in each message class.
Thanks in advance
class Messages{
private function __construct(){}
public static function get($type) {
return new $type;
}
}
class Message_1 extends Elements{
protected $root;
public function __construct() {
parent::__construct();
$this->root = $this->createElement("message1");
}
public function add_anotherElement(){
$this->root->appendChild($this->add_anotherElementBlock("foo", "bar"));
}
public function add_element(){
$this->root->appendChild($this->add_someElementBlock("foo", "bar"));
}
public function save(){
return $this->saveXML($this->root);
}
}
class Message_2 extends Elements {
protected $root;
public function __construct() {
parent::__construct();
$this->root = $this->createElement("message2");
}
public function add_elements(){
$this->root->appendChild($this->add_anotherElementBlock("foo", "bar"));
$this->root->appendChild($this->add_someElementBlock("foo", "bar"));
}
public function save(){
return $this->saveXML($this->root);
}
}
class Elements extends DOMDocument{
public function __construct() {
parent::__construct();
}
public function add_someElementBlock($foo, $bar) {
$node = $this->createElement("root");
$attr = $this->createAttribute("id");
$attr->value = $foo;
$node->appendChild($attr);
$subnode = $this->createElement("sub",$bar);
$node->appendChild($subnode);
return $node;
}
public function add_anotherElementBlock($foo, $bar) {
$node = $this->createElement("anotherRoot");
$subnode = $this->createElement("anotherSubNode",$bar);
$attr = $this->createAttribute("anotherAttribute");
$attr->value = $foo;
$subnode->appendChild($attr);
$node->appendChild($subnode);
return $node;
}
}
$message1 = Messages::get('Message_1');
$message1->add_element();
$message1->add_anotherElement();
$message2 = Messages::get('Message_2');
$message2->add_elements();
echo "<pre>";
print_r(htmlentities($message1->save()));
echo "</pre>";
echo "<hr />";
echo "<pre>";
print_r(htmlentities($message2->save()));
echo "</pre>";
source
share