13.3. Code Example
The music website has some social networking type features available to the visitors of the website. The newest feature to integrate is an activity stream, which shows the most recent purchases on the home page. The hope is that people will click through to recent purchases, possibly buying their own copy.
The first step to putting the sales of CDs into the activity stream is having a CD object that is based on the Observer Design Pattern:
class CD
{
public $title = '';
public $band = '';
protected $_observers = array();
public function __construct($title, $band)
{
$this->title = $title;
$this->band = $band;
}
public function attachObserver($type, $observer)
{
$this->_observers[$type][] = $observer;
}
public function notifyObserver($type)
{
if (isset($this->_observers[$type])) {
foreach ($this->_observers[$type] as $observer)
{
$observer->update($this);
}
}
}
public function buy()
{
//stub actions of buying
$this->notifyObserver('purchased');
}
}
The constructor simply assigns the title and band name to the public variables of $title and $band.
The attachObserver() public method takes two parameters. The first is the $type parameter. Because there are many types of state changes that a CD can have, the type of notification is further specialized by having the $type parameter. The second parameter is the Observer class that will be added to the protected $_observers array. Note, the $type variable determines the key of the first level of the array. Then all types ...
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