19.3. Code Example
For auditing, each new CD purchase on your e-commerce website must be logged. This information is then archived. In the case that there are ever any inconsistent inventory counts, the log file can be examined to see if a CD was actually purchased.
In order to accomplish this, the CD object must accept Visitors:
class CD
{
public $band;
public $title;
public $price;
public function __construct($band, $title, $price)
{
$this->band = $band;
$this->title = $title;
$this->price = $price;
}
public function buy()
{
//stub
}
public function acceptVisitor($visitor)
{
$visitor->visitCD($this);
}
}
The CD object receives the band, title, and price of the CD on instantiation. The constructor applies each of those to the public $band, $title, and $price properties.
The CD also has a public method called buy(). In this example, the purchase logic is left out. This stub method is for demonstration purposes.
The CD has one more public method, called acceptVisitor(). This method is required in order to comply with the Visitor Design Pattern. It accepts an instance of a Visitor from the $visitor parameter. Inside the method, the Visitor's public visitCD() method is called. It is passed an instance of the CD class, using the $this variable.
The logging Visitor contains the following code:
class CDVisitorLogPurchase { public function visitCD($cd) { $logline = "{$cd->title} by {$cd->band} was purchased for {$cd->price} "; $logline .= "at " . sdate('r') . "\n"; file_put_contents('/logs/purchases.log', ...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