Skip to content
laxertu edited this page Apr 6, 2018 · 11 revisions

An example of use:

# My system. Let's imagine a book catalog
class MySystemBook
{
    public $title;
    public $author;
    public $ISBN;
    public function __construct($title, $author, $isbn)
    {
        $this->title  = $title;
        $this->author = $author;
        $this->ISBN   = $isbn;
    }
}


class MySystemCatalogue
{
    /** @var  MySystemBook[] */
    public $books;
    public function __construct($books)
    {
        $this->books = $books;
    }
}

# Let's add wrappers to data tree

class BookNode extends Node
{

    public function __construct(MySystemBook $book)
    {
        $this->setName('Book');

        $this->setChildElement('isbn', $book->ISBN);
        $this->setChildElement('title', $book->title);
        $this->setChildElement('author', $book->author);
    }

}


class CatalogueXMLMessage extends NodeList
{

    public function __construct(MySystemCatalogue $catalogue)
    {
        foreach ($catalogue->books as $book)
        {
            $this->addNode(new BookNode($book));
        }
    }

}

# let's make a catalogue
$q     = new MySystemBook('Q', 'Luther Blisset', '123');
$bible = new MySystemBook('The Holy Bible', 'Various', '456');

$mySystemCatalogue = new MySystemCatalogue([$q, $bible]);

# XML generation
$xmlCatalogue = new CatalogueXMLMessage($mySystemCatalogue);

$formatter = new XMLFormatter();
$xml = $formatter->buildContent($xmlCatalogue);

$xml contains (but in one single line)

   <CatalogueXMLMessage>
	<Book>
		<isbn>123</isbn>
		<title>Q</title>
		<author>Luther Blisset</author>
	</Book>
	<Book>
		<isbn>456</isbn>
		<title>The Holy Bible</title>
		<author>Various</author>
	</Book>
</CatalogueXMLMessage>

Note that a DataTree defaults to class name when node name is not setted.

With JSON formatter:

$formatter = new JsonFormatter();
$json = $formatter->buildContent($xmlCatalogue);
echo $json;

$json contains (in one single line):

{"CatalogueXMLMessage":[
    {
        "Book":{
            "isbn":"123",
            "title":"Q",
            "author":"Luther Blisset"
        }
    },
    {
        "Book":{
            "isbn":"456",
            "title":"The Holy Bible",
            "author":"Various"
        }
    }
]}
Clone this wiki locally