Here is another option that allows to add more data structures without adding all of the logic to XMLWriter.
First define an interface for your data structure classes:
interface XMLWritable {
public function writeTo(XMLWriter $writer);
}
Now add a method to an extended XMLWriter that can accept it. Additionally the constructor of the extended XMLWriter can do some bootstrapping:
class MyXMLWriter extends XMLWriter {
public function __construct(
string $uri = 'php://output', string $version = '1.0', string $encoding = 'UTF-8'
) {
$this->openURI($uri);
$this->setIndent(true);
$this->startDocument($version, $encoding);
}
public function write(XMLWritable $item): self {
$item->writeTo($this);
return $this;
}
}
Next you implement the interface into specific data classes or serializers. You can add classes as needed. The XMLWriter does not need to know about them.
class ExampleItem implements XMLWritable {
private $_content;
public function __construct(string $content) {
$this->_content = $content;
}
public function writeTo(XMLWriter $writer) {
$writer->writeElement('example', $this->_content);
}
}
Using them looks like this:
$writer = new MyXMLWriter();
$writer->startElement('root');
$writer
->write(new ExampleItem('one'))
->write(new ExampleItem('two'));
$writer->endElement();