7.3. Code Example

This particular website has a feature to create playlists from MP3 files. These could come from the visitor's hard drive or from locations on the Internet. The visitor has the choice to download the playlist in either M3U or PLS format. (The code example will only show the creation of the playlist for brevity.)

The first step is to create the Playlist class:

class Playlist
{
    private $__songs;

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

    public function addSong($location, $title)
    {
        $song = array('location'=>$location, 'title'=>$title);
        $this->__songs[] = $song;
    }

    public function getM3U()
    {
        $m3u = "#EXTM3U\n\n";

        foreach ($this->__songs as $song) {
            $m3u .= "#EXTINF:−1,{$song['title']}\n";
            $m3u .= "{$song['location']}\n";
        }
return $m3u;
    }

    public function getPLS()
    {
        $pls = "[playlist]\nNumberOfEntries=" . count($this->__songs) . "\n\n";

        foreach ($this->__songs as $songCount=>$song) {
            $counter = $songCount + 1;
            $pls .= "File{$counter}={$song['location']}\n";
            $pls .= "Title{$counter}={$song['title']}\n";
            $pls .= "Length{$counter}=−1\n\n";
        }

        return $pls;
    }
}

The Playlist object stores an array of songs, which is initialized by the constructor.

The addSong() public method accepts two parameters, a location of the MP3 file and the title of the file. These are formed into an associative array and then added to the internal songs array.

The requirements state that the playlist must be available in both M3U and PLS formats. For this, the Playlist class has ...

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.