16.3. Code Example
Visitors to the CD Website can purchase more than one CD at a time. In fact, they're encouraged to do just that. You should provide a shopping cart for them to store their purchases in. Since you work with a live inventory, it is important to update the inventory listing as soon as the CDs are purchased. To do this, you need to connect to the MySQL database and update the quantity for that CD. With your object-oriented approach, you could potentially create multiple connections to the database that are not needed. Instead, the inventory connection is based on the Singleton Design Pattern:
class InventoryConnection
{
protected static $_instance = NULL;
protected $_handle = NULL;
public static function getInstance()
{
if (!self::$_instance instanceof self) {
self::$_instance = new self;
}
return self::$_instance;
}
protected function __construct()
{
$this->_handle = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('CD', $this->_handle);
}
public function updateQuantity($band, $title, $number)
{
$query = "update CDS set amount=amount+" . intval($number);
$query .= " where band='" . mysql_real_escape_string($band) . "'";
$query .= " and title='" . mysql_real_escape_string($title) . "'";
mysql_query($query, $this->_handle);
}
}
The first public method of the InventoryConnection class is a static method called getInstance(). This checks to see if the protected static variable named $_instance has an instance of the class itself. If it does not, then a new ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access