11.3. Code Example

Part of the example website's job is to show all the CDs from a particular artist or band. This information is stored in a MySQL database. Some visitors may want to search the database by the band name and get a summary of all of the CDs that particular artist has released. This is the perfect example of the Iterator Design Pattern in practice.

First, our semi-standard CD class:

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

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

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

In this example of the CD class, you're using public variables for the band, title, and track list. The constructor creates the instance and assigns the band and title internally. The addTrack() function accepts the $track variable and uses that to add to the track list.

The next class to make is the Iterator. In this example, the SPL Iterator is being implemented. Because of that, you're required to have the current(), key(), rewind(), next(), and valid() public methods.

class CDSearchByBandIterator implements Iterator { private $__CDs = array(); private $__valid = FALSE; public function __construct($bandName) { $db = mysql_connect('localhost', 'user', 'pass'); mysql_select_db('test'); $sql = "select CD.id, CD.band, CD.title, tracks.tracknum, "; $sql = "tracks.title as tracktitle "; $sql .= "from CD left join tracks on CD.id=tracks.cid where band='"; ...

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.