10.3. Code Example

The website in this example has decided to jump on the bandwagon to merge the CD buying experience and social networking. Users who sign up for the website can have their own profile page. They'll be able to add advanced functionality like HTML, widgets, and listings of their favorite CDs.

In the first iteration, users can create their profile and add their favorite CD title to their profile. The first piece of functionality is the User class:

class User
{
    protected $_username = '';

    public function __construct($username)
    {
        $this->_username = $username;
    }
public function getProfilePage()
    {
        //In lieu of getting the info from the DB, we mock here
        $profile = "<h2>I like Never Again!</h2>";
        $profile .= "I love all of their songs. My favorite CD:<br />";
        $profile .= "{{myCD.getTitle}}!!";

        return $profile;
    }
}

Most of the User class is mocked up for this example. When creating an instance of the User class, the username is assigned to the protected $_username variable. In a non-mock example, some logic may be placed here to query the database and initialize the User object with the proper values. The getProfilePage() function is also a mock method. It returns a hard-coded profile. The important portion of this example to note, however, is the {{myCD.getTitle}} string. This represents the template language that will be interpreted later. The getProfilePage() just returns what the user has specified as their profile page.

In order to retrieve CD information for the user, ...

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.