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

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

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