Adobe Air Adobe Flash CS4 Flex Flash Builder Flash Catalyst

Contact me at : hello[at]gauravjassal[dot]com

Webdevelopment Blog



Observer pattern in PHP part 1
November 9,2009 at 12:00 pm | PHP | No Coments

The Observer pattern defines a mechanism by which components can opt-in to receive messages when a target object changes its state. Its works similar to Listening to a Change event for a object or Trigger in a database, which runs a stored procedure when a table row is modified.

This is very convenient in many situations. It is especially useful when it comes to working with Web-based user interfaces and system loggers. In these cases there are different independent objects that need to reflect any eventual changes by notifying a core module, which will take a course of action in accordance with the relevance of these modifications. Being an actionscript developer I use this pattern a lot as events. In actioscripts an object can listen to an event and execute a code when ever that particular event get triggered.

The Observer Pattern is designed to help cope with one to many relationships between objects, allowing changes in an object to update many associated objects.

In this article I am going to show you two examples.

    • First example will demonstrate how to create Observable and Observer Class to listen to any changes in the object.
    • Secondly I am going to demonstrate Observer classes available in Standard PHP Library (SPL)

    The example that I am going to work on is about a Birthday party and to notify all attendees if there is a change of location. Here the Birthday Party Class will be our Observable and Attendees will be Observing to any change in the event.

    Example 1

    Observable.php

    
    <?php
    
    /**
     *  @name Observable
     *  @author Gaurav Jassal
     *  @access public
     *  @copyright gauravjassal@gmail.com
     *  @example
     */
    
    class Observable {
        /**
        * Protecetd
        * $observers an array of Observer objects to notify
        */
        protected $observers;
    
        /**
        * Protected
        * $state store the state of this observable object
        */
        protected $state;
    
        /**
        * Constructs the Observerable object
        */
        function Observable () {
            $this->observers=array();
        }
    
        /**
        * Calls the update() function using the reference to each
        * registered observer - used by children of Observable
        * @return void
        */
        function notifyObservers () {
            $observers=count($this->observers);
            for ($i=0;$i<$observers;$i++) {
                $this->observers[$i]->update();
            }
        }
    
        /**
        * Register the reference to an object object
        * @return void
        */
        function addObserver (& $observer) {
            $this->observers[]=& $observer;
        }
    
        /**
        * Returns the current value of the state property
        * @return mixed
        */
        function getState () {
            return $this->state;
        }
    
        /**
        * Assigns a value to state property
        * @param $state mixed variable to store
        * @return void
        */
        function setState ($state) {
            $this->state=$state;
        }
    }
    ?>
    

    Observer.php

    <?php
    /**
     *  @name Observer
     *  @author Gaurav Jassal
     *  @access public
     *  @copyright gauravjassal@gmail.com
     *  @example
     */
    class Observer {
        /**
        * Private
        * $subject a child of class Observable that we're observing
        */
        var $subject;
    
        /**
        * Constructs the Observer
        * @param $subject the object to observe
        */
        function Observer (& $subject) {
            $this->subject=& $subject;
    
            // Register this object so subject can notify it
            $subject->addObserver($this);
        }
    
        /**
        * Abstract function implemented by children to repond to
        * to changes in Observable subject
        * @return void
        */
        function update() {
            trigger_error ('Update cannot be implemented');
        }
    }
    ?>
    

    Here is our BirthdayParty class that extends Observable class. Notice in the construction we have declare that this class is set to be observed by calling Observable::Observable();. In the changeLocation function after changing the location we need to set the state of the event other we won’t be able to differentiate between various events. addAttende add a person to the Birthday party observer list.

    
    <?php
    /**
     * 	@name BirthdayParty
     *  @author Gaurav Jassal
     *  @access public
     *  @copyright gauravjassal@gmail.com
     *
     */
    class BirthdayParty extends Observable {
    
    	protected $party_location = "Oxford Street";
    
    	/**
    	 * Constructs the BirthdayParty
    	 * @return void
    	 */
    	function BirthdayParty(){
    		// Declare this class Observable
    		Observable::Observable();
    	}
    
    	/**
    	 * Function to change the location of
    	 * the party. Once the location is changed it
    	 * nofiys all observers.
    	 * @return
    	 */
    	function changeLocation($location){
    		echo('inside $bp->changeLocation() New location for the party is ' . $location);
    		$this->setPartyLocation($location);
    		$this->setState('LOCATION_CHANGED');
    		$this->notifyObservers();
    	}
    
    	/**
    	 * Getter function for party location
    	 * @return String party_location
    	 */
        public function getPartyLocation() {
            return $this->party_location;
        }
    
    	/**
    	 * Setter function to set the new location for the party
    	 * @param string $party_location
    	 * @return void
    	 */
        public function setPartyLocation($party_location) {
            $this->party_location = $party_location;
        }
        /**
         * Adds new attend to party obsever list
         * sets the attende name
         * @param string $name
         * @return  void
         */
    	function addAttendes($name)
    	{
    		new Attendes($this,$name);
    	}
    }
    ?> 
    

    Now we have to create a class for attends that will observe the birthday party and will get notified if the location gets changed. The update function listens to the event and gets triggerd when the party location is changed.

    <?php
    /**
     *  @name Attendes
     *  @author Gaurav Jassal
     *  @access public
     *  @copyright gauravjassal@gmail.com
     *
     */
    class Attendes extends Observer {
    
    	protected $attende_name;
    	/**
        * Constructs the Attendes object passing the parent
        * the subject observable object
        */
    	function Attendes(& $party,$name)
    	{
    		Observer::Observer($party);
    		$this->attende_name = $name;
    	}
    
    	/**
    	 * Implements the parent update(0 method
    	 * @return void
    	 */
    	function update(){
    		// check if the location is changed
    
    		if($this->subject->getState() == "LOCATION_CHANGED"){
    			$this->notifyAll();
    		}
    	}
    
    	/**
    	 * Function trigger notification to all users.
    	 * @return void
    	 */
    	function notifyAll()
    	{
    		echo "<br> Mr." . $this->attende_name . " the location for my birthday party is changed " . $this->subject->getPartyLocation();
    	}
    }
    ?>
    

    Usage

    <?php
    	error_reporting(E_ALL);
    	ini_set("display_errors", 1); 
    
    	require_once('Observable.php');
    	require_once('Observer.php');
    	require_once('Birthday.php');
    	require_once('Attendes.php');
    
    	$bp = new Birthday();
    
    	$bp->addAttendes("Gaurav");
    	$bp->addAttendes("Ronnie");
    	$bp->addAttendes("Suman");
    	$bp->addAttendes("Rajan");
    
    	echo "<h1>Eample 1 </h1>";
    	echo "Original Location " . $bp->getPartyLocation() . "<br>";
    	$bp->changeLocation("William St.");
    
    ?> 
    

    Results

    Eample 1
    Original Location Oxford Street
    inside $bp->changeLocation() New location for the party is William St.
    Mr.Gaurav the location for my birthday party is changed William St.
    Mr.Ronnie the location for my birthday party is changed William St.
    Mr.Suman the location for my birthday party is changed William St.
    Mr.Rajan the location for my birthday party is changed William St.

    Leave a Reply

    Recent Blog Entry

    In the second example I am going to use Standard PHP Library (SPL) to notify all attendees about the party location change. SPL has 2 interfaces and a Class for Observer.


    Read More

    The Observer pattern defines a mechanism by which components can opt-in to receive messages when a target object changes its state. Its works similar to Listening to a Change event for a object or Trigger in a database


    Read More

    Multi touch is a method of interaction with a computer screen or your smartphones like iPhone or Palm Pre. Its allows the user to interact with your device by placing one or more than one finger on the screen.


    Read More

    Featured Projects

    My Blog

    Contact Information

    © 2008 Gaurav Jassal