15.3. Code Example

Because the web site is so great, sales have grown at the CD store. Expansion is inevitable. The website has been executing normal sales every day. The good working code is simple. First, you have the object that represents a CD that a visitor can purchase:

class CD
{
    protected $_title = '';
    protected $_band = '';
    protected $_handle = null;

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

    public function buy()
{
        $this->_connect();

        $query = "update CDs set bought=1 where band='";
        $query .= mysql_real_escape_string($this->_band, $this->_handle);
        $query .= "' and title='";
        $query .= mysql_real_escape_string($this->_title, $this->_handle);
        $query .= "'";

        mysql_query($query, $this->_handle);
    }

    protected function _connect()
    {
        $this->_handle = mysql_connect('localhost', 'user', 'pass');
        mysql_select_db('CD', $this->_handle);
    }
}

The constructor builds the CD by assigning its two parameters, $title and $band, to the protected variables $_title and $_band, respectively.

The other public method is called buy(). This executes the sale. The first step is calling the protected _connect() method. _connect() creates a connection to the local MySQL database using the proper credentials. Next, buy() creates a query to update the CD row and set it to bought. Finally, the query is executed, and the CD purchase is complete.

The current code to buy a CD is pretty streamlined:

$externalTitle = 'Waste of a Rib'; $externalBand = 'Never Again'; ...

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.