18.3. Code Example

The e-commerce website has expanded. Visitors to the website can now order many new items, including cases of cereal endorsed by the band. Who knew that these would be in high demand! Now, you can create classes that can hold the price for themselves as well as add tax. You used to be able to apply a flat tax — but now with food sales — each class has to hold the tax for itself. Additionally, some items are pretty large. For example, some of the cases of product require a premium to cover handling. This is added to the final purchase price.

This particular example will differ from most by having more structure. Generally, the simplest version of a class demonstrating a design pattern is created. Best practices, such as enforcing access using interfaces, are generally skipped. However, for this particular design pattern, the controls are so strongly specified that I thought it would be best to illustrate it with a more structured approach using abstract classes and methods.

The first step is to define a base class using the Template Design Pattern to process any of the sale items:

abstract class SaleItemTemplate
{
    public $price = 0;

    public final function setPriceAdjustments()
    {
        $this->price += $this->taxAddition();
        $this->price += $this->oversizedAddition();
    }

    protected function oversizedAddition()
    {
        return 0;
    }

    abstract protected function taxAddition();
}

The SaleItemTemplate is a simple class. It is an abstract class, so it enforces the requirement to be ...

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.