15.04.2010
|
The observer pattern gives you another way to avoid tight coupling between components. This pattern is simple: One object makes itself observable by adding a method that allows another object, the observer, to register itself. When the observable object changes, it sends a message to the registered observers. What those observers do with that information isn't relevant or important to the observable object. The result is a way for objects to talk with each other without necessarily understanding why. |
Our example is related to an user class. When a new user is added, the observer must be notified (we attached it before this).
interface IObserver { function notify($sender_obj); } class Log_System implements IObserver { public function notify($sender_obj) { echo "LOG: ".get_class($sender_obj)." Add Name: ".$sender_obj->get_name()."\n"; } } class User { protected $_observers; protected $_name; public function get_name() { return $this->_name; } public function add_user($name) { $this->_name = $name; $this->_notify_observers(); } public function attach_observer(IObserver $observer) { $this->_observers[] = $observer; } protected function _notify_observers() { foreach ($this->_observers as $observer) { $observer->notify($this); } } } $newuser = new User(); $newuser->attach_observer(new Log_System); $newuser->add_user("John Doe");
Run it in a terminal (php observerpat.php) and you'll get the echo result. The Observer (Log_System) will receive an User object and extract the information as necessary using object methods (get_name() for example).
Credits/References: