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

12.3. Code Example

The example website allows bands to come in and manage their music collection. It also allows them to update their profile, change information about their band, and update their CD information. Recently, artists were allowed to upload a collection of MP3s as well as ship CDs from the website. Because of this, the website needs to keep CDs and their MP3 counterparts in sync with each other.

The initial version of the website allowed the band to change its band name from the profile page or from an individual CD itself. The CD object had a method that would accept the band change and update it in the database:

class CD
{
    public $band = '';
    public $title = '';

    public function save()
{
        //stub - writes data back to database - use this to verify
        var_dump($this);
    }

    public function changeBandName($newName)
    {
        $this->band = $newName;
        $this->save();
    }
}

This simple class just demonstrates that the CD object can have a band and title. Then, the function changeBandName() takes a new band name parameter. It sets it in the object and then calls the save() method. For demonstration purposes, the save() method is just a stub. You dump the instance to verify that the changes have been made.

With the addition of our MP3 archive, another similar object needs to be created to work with that archive. The artist must also be able to change their band name on the MP3 archive page. The band name must also then change in the CD that is associated with it.

The Mediator Design Pattern ...

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