17.3. Code Example
The website works heavily with AJAX. From time to time, it's necessary for the CD object to generate an XML version of itself. This is returned to the JavaScript front end to be processed.
The CD object is:
class CD
{
public $title = '';
public $band = '';
public function __construct($title, $band)
{
$this->title = $title;
$this->band = $band;
}
public function getAsXML()
{
$doc = new DomDocument();
$root = $doc->createElement('CD');
$root = $doc->appendChild($root);
$title = $doc->createElement('TITLE', $this->title);
$title = $root->appendChild($title);
$band = $doc->createElement('BAND', $this->band);
$band = $root->appendChild($band);
return $doc->saveXML();
}
}
The constructor takes two parameters, the $title and $band, and assigns them to the public properties of the class. The getAsXML() public method creates a new DomDocument. It then builds each individual node and adds it to the DomDocument. Finally, the saveXML() method is called, which returns a string representation of the XML file. This is sent as the return parameter from the getAsXML() method.
To use this, the code is pretty straightforward:
$externalBand = 'Never Again'; $externalTitle = 'Waste of a Rib'; $cd = new CD($externalTitle, $externalBand); print $cd->getAsXML();
A new developer has joined the team. He has some great experience with AJAX and says that you could be doing this a little bit better. Additional flexibility is needed for the website's AJAX functionality, including being able ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access