User Tools

Site Tools


php:observer

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

php:observer [2013/03/16 17:40] (current)
Line 1: Line 1:
 +==== OBSERVER PATTERN ====
 +15.04.2010
  
 +<columns 100% first column attributes 30% second column attributes 70%>
 +{{:​php:​observerpat.png|}}
 +<​newcolumn>​
 +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.
 +</​columns>​
 +
 +Our example is related to an user class. When a new user is added, the observer must be notified (we attached it before this).
 +
 +<code php>
 +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");
 +</​code>​
 +
 +
 +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:​**
 +
 +[[http://​giorgiosironi.blogspot.com/​search/​label/​patterns|Giorgio Sironi]] \\ 
 +[[https://​www.ibm.com/​developerworks/​library/​os-php-designptrns/#​N10177|Five Common PHP Design Patterns ]]
php/observer.txt ยท Last modified: 2013/03/16 17:40 (external edit)