6.3. Code Example

In this example, the application is processing compact discs (CDs). It must have a method to add tracks to the CD and a way to show the track list from the CD. The client has specified that the CD track list should be displayed in a single line with each track being prefixed by the track number.

class CD
{
    public $trackList;

    public function __construct()
    {
        $this->trackList = array();
    }

    public function addTrack($track)
    {
        $this->trackList[] = $track;
    }

    public function getTrackList()
    {
        $output = '';

        foreach ($this->trackList as $num=>$track) {
            $output .= ($num + 1) . ") {$track}. ";
        }

        return $output;
    }
}

The CD class contains a public variable called $trackList, which will store an array of tracks added to the CD object. The constructor initializes this variable. The addTrack() method simply adds a track to the CD object's trackList array. Finally, the getTrackList() method loops through each of the tracks on the CD and compiles them into a single string in the format that was specified.

To use this CD object, the following code is executed:

$tracksFromExternalSource = array('What It Means', 'Brr', 'Goodbye');

$myCD = new CD();

foreach ($tracksFromExternalSource as $track) {
    $myCD->addTrack($track);
}

print "The CD contains

This works fine for this example. However, the requirements have changed slightly. Now, each track in the output needs to be in uppercase for just this instance of output. Because its best practice not to modify the base class or create a new ...

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.