8.3. Code Example

The website passes its inventory to a different system in the company nightly as part of a required audit. This other system will accept the request via a post to its web service. It is an older system, however, and works with only uppercase strings. The code needs to acquire CD objects, apply uppercase to all their properties, and create a well-formed XML document to be posted to the web service.

The following is a simple example of a CD class:

class CD
{
    public $tracks = array();
    public $band = '';
    public $title = '';

    public function __construct($title, $band, $tracks)
    {
        $this->title = $title;
        $this->band = $band;
        $this->tracks = $tracks;
    }
}

When a new CD is instantiated, the constructor adds the title, band, and track list to the CD object. To build the CD object, the steps are pretty simple:

$tracksFromExternalSource = array('What It Means', 'Brrr', 'Goodbye');
$title = 'Waste of a Rib';
$band = 'Never Again';

$cd = new CD($title, $band, $tracksFromExternalSource);

To format the CD object for the external system, two additional classes will be created. The first one will be used to prepare the properties of the CD object. The required format is uppercase. The other class will be responsible for building an XML document out of the CD object. This class will return a string of the entire document.

NOTE

It is important to note that two classes will be created for maximum reusability. It may be tempting to combine both of these steps into one class, but that ...

Get Professional PHP Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.