有没有一种简单的方法来创建自定义 PHP XML 编写器函数?

Is there a simple way to create a custom PHP XML writer function?

我正在开发一个 PHP 网络 API(使用 Laravel 流明)输出 XML 但是编写 XML 结构和属性正在获取失控了,有没有一种简单的方法来创建缩短代码库的自定义函数?

我正在使用 PHP 的 $xml = new \XMLWriter(); 并编写如下代码:

$xml->startElement('DataStructure');
$xml->writeAttribute('version', "1.0");

我想做的是:

$xml->startElement('DataStructure');
$this->api_version();

where

function api_version() {
    $xml->writeAttribute('version', "1.0");
}

您可以从 XMLWriter 继承以满足您的需要。您可以添加一个像 addDatastructure() 这样的方法,然后像这样使用它:

class ExtendedWriter extends XMLWriter {
    public function addDatastructure($version): self {
        $this->startElement('DataStructure');
        $this->writeAttribute('version', $version);

        return $this;
    }
}

// And use it like a so:
$writer = new ExtendedWriter;
$writer->addDatastructure($version);

您可以添加任何您需要的功能。这使您的创作代码更少,但也增加了可重用性。

这是另一个选项,它允许添加更多数据结构而无需将所有逻辑添加到 XMLWriter。

首先为你的数据结构定义一个接口类:

interface XMLWritable {
    public function writeTo(XMLWriter $writer); 
}

现在向可以接受它的扩展 XMLWriter 添加一个方法。此外,扩展的 XMLWriter 的构造函数可以进行一些引导:

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;
    }
}

接下来将接口实现到特定数据 类 或序列化程序中。您可以根据需要添加 类。 XMLWriter 不需要知道它们。

class ExampleItem implements XMLWritable {

    private $_content;

    public function __construct(string $content) {
        $this->_content = $content;
    }

    public function writeTo(XMLWriter $writer) {
        $writer->writeElement('example', $this->_content);
    }
}

它们的使用方式如下:

$writer = new MyXMLWriter();
$writer->startElement('root');
$writer
  ->write(new ExampleItem('one'))
  ->write(new ExampleItem('two'));
$writer->endElement();