Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^182) CHAPTER 12 ■ SPL ARRAY OVERLOADING
So this could be useful, but it’s hardly worth getting up off the couch for. The power of the
ArrayObject object comes when you extend it. A common use for a web application is a shopping
cart, so let’s take a look at how to build a shopping cart collection.


Building an SPL Shopping Cart


All shopping carts are not created equal. Some just handle lists of items; others handle all kinds
of advanced logic. By using an SPL class, you can include this logic, without needing to give up
the ease of iteration and counting that you would have with a plain array.
In this example, you will create two classes: a generic Product class to encapsulate a single
product and its attributes, and a shopping Cart class.
First, you need to define the properties of a product, as shown in Listing 12-3. For this
example, you will have a part number, a price, and a description. The number of properties
that you use is entirely up to you, so keep in mind that this example is extensible.

Listing 12-3. A Product Class (Product.php)

class Product {

protected $_partNumber, $_description, $_price;

public function __construct($partNumber, $description, $price) {
$this->_partNumber = $partNumber;
$this->_description = $description;
$this->_price = $price;
}

public function getPartNumber() {
return $this->_partNumber;
}

public function getDescription() {
return $this->_description;
}

public function getPrice() {
return $this->_price;
}

}

Next, extend ArrayObject to create a Cart class, as shown in Listing 12-4.

McArthur_819-9C12.fm Page 182 Thursday, February 28, 2008 7:51 AM

Free download pdf