O'Reilly logo

Professional PHP Design Patterns by Aaron Saray

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required