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 2
November 9,2009 at 12:18 pm | PHP | 2 Comments

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.

  • interface SplObserver
    • Had update($subject) method
  • interface SplSubject
    • Has attach($observer) method
    • Has detach($observer) method
    • Has notify() method
  • class SplObjectStorage

Here is our BirthdayParty class that implements SplSubject interface.

<?php
/**
 *  @name BirthdayParty
 *  @author Gaurav Jassal
 *  @access public
 *  @copyright gauravjassal@gmail.com
 *
 */

class BirthdayParty implements SplSubject {

    protected $party_location = "Oxford Street";

    protected $observers = array();

	/**
	 * Add the observer to the list
	 * @param SplObserver $observer
	 * @return void
	 */
    public function attach(SplObserver $observer) {
        $this->observers[] = $observer;
    }
    /**
     * Remove observer for the list
     * @param SplObserver $observer
     * @return
     */
    public function detach(SplObserver $observer) {
    	// we are not going to remove any observer in this example
    }

	/**
	 * Send notification the observer
	 * @return void
	 */
    public function notify() {
        foreach ($this->observers as $key=>$value) {
            $value->update($this);
        }
    }
	/**
	 * Getter function for party location
	 * @return string
	 */
    public function getPartyLocation() {
        return $this->party_location;
    }
	/**
	 * Setter function for party location
	 * @param string $party_location
	 * @return void
	 */
    public function setPartyLocation($party_location) {
        $this->party_location = $party_location;
		$this->notify();
    }
}
?>

Our second Attendee class that implements SplObserver. When ever there is a change in the party location the update method gets triggered.

<?php

class Attendes implements SplObserver{
	protected $id;

	public function __construct($id)
	{
		$this->id = $id;
	}

	public function update(SplSubject $s)
	{
		echo "<br> " . $this->id . " has been notified about the new location :  " . $s->getPartyLocation();
		//return;
	}
}
?>

Usage

<?php
	error_reporting(E_ALL);
	ini_set("display_errors", 1); 

	require_once('BirthdayParty.php');
	require_once('Attendes.php');
	echo "<h1>Eample 2 </h1>";
	$bp = new BirthdayParty();

	$bp->attach(new Attendes("Gaurav"));
	$bp->attach(new Attendes("Ronnie"));
	$bp->attach(new Attendes("Katie"));
	$bp->attach(new Attendes("Suman"));
	$bp->attach(new Attendes("Devang"));

	$bp->setPartyLocation("King Williams St.");

?>

Results
Eample 2

Gaurav has been notified about the new location : King Williams St.
Ronnie has been notified about the new location : King Williams St.
Katie has been notified about the new location : King Williams St.
Suman has been notified about the new location : King Williams St.
Devang has been notified about the new location : King Williams St.

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.

    Sending email using PHP on IIS server
    October 31,2009 at 5:16 pm | PHP | No Coments

    Recently I had to deploy two of my PHP projects to a IIS (Internet Information Service) on windows. Everything was working fine but one issue gave me a headache. And the issue was that php was not delivering emails. I did some research work and found that on windows we have to set sendmail_from address before sending email.

    Just simply add this line before sending email.

    ini_set("sendmail_from", "fromname@domain.com");
    
    Why use Constraints in SQL ?
    January 27,2009 at 5:52 am | MySQL, PHP, PostgresSQL | 4 Comments

    Constraints enables business rules to be enforced by the database instead of via application code. Through the judicious use of constraints, application and SQL coding can be minimized and data integrity can be maximized. Constraints may be applied to columns in the form of uniqueness requirements, relational integrity constraints to other tables/rows, allowable values and data types.For example, a column containing a product price should probably only accept positive values. But there is no standard data type that accepts only positive numbers. Another issue is that you might want to constrain column data with respect to other columns or rows. For example, in a table containing product information, there should be only one row for each product number. (more…)

    What Makes a Great Developer?
    January 23,2009 at 5:21 pm | Actionscript 2, Actionscript 3, Flex 3, JQuery, PHP | No Coments

    What makes a truly great developer? Some might say a positive attitude. Some might say a high-sugar, high-caffeine, high-bacon diet. Some might say an absence of sunlight and as many monitors as a desk can support.

    Certainly, everyone has anecdotes about developers they’ve worked with who they thought were brilliant. Unfortunately, most of the time that judgement is made not based on code quality, or hitting of deadlines, but on less relevant criteria, like whether or not the developer knew the names of their colleagues, how many lines of code they output or how confident they sounded when talking about their work.

    Unfortunately, the best developers don’t always come across positively. While this list may not be applicable to every development environment, here are a few of the traits to look out for to spot a great developer.

    Pessimistic

    Great developers are almost always pessimistic with regard to their work. That doesn’t mean they’re not upbeat, lively or even cheerful – just that they will always be thinking about what can go wrong and how it can be dealt with.

    They’ll assume that at some point they’ll need to undo work already completed, that hardware will fail, that all security will be compromised, and that your office will burn to the ground. The really brilliant ones will assume that will all happen on the same day. And they won’t be happy until there is a specific, actionable, testable – and fully tested – plan for dealing with these sorts of issues. Even then they won’t be completely happy.

    Pessimistic developers will be the ones that find constant flaws in ideas, and the important thing to remember when working with them is that they’re not doing that to tear down other people’s ideas – they’re doing it to ensure that the ideas that turn into projects are properly thought through and that as many problems as possible have been anticipated in advance. That neurotic, paranoid, pessimistic attitude is exactly what you should be looking for if what you want from your developers is robust, secure, reliable code.

    By contrast, an optimistic developer will be more likely to simply assume code will work, or that it is secure, or give a deadline for a project without considering all the potential pitfalls.

    Likely to be heard saying: “And what happens when that goes wrong?”

    Lazy

    Laziness is not usually viewed as a desirable trait, and in this case I don’t mean turns-up-late-and-pretends-to-work laziness or just-move-that-logic-to-the-view laziness – both entirely unwanted. I mean a desire to not do tasks that are repetitive, or to waste time doing things a machine can do for you, or even to avoid future work by writing better code now. A lazy developer is one that builds a reusable code library, or wants a fully automated build process rather than a manual copy-and-paste one, or wants comprehensive automated unit testing, or writes code to be scalable even though that wasn’t a requirement (rather than revisit it later).

    As a bonus, a lazy developer is also usually one who will try and keep a project focussed on its core goals, rather than try and cram more work into the same time, providing a buffer against feature creep.

    For example, when writing a category structure, a lazy developer might be likely to assume a many-to-many relationship between parent and child categories, even though the project specification says it will be a one-to-many relationship. Why? Because it might be needed one day and it would be better to write it that way from the start than to revisit it later.

    Likely to be heard saying: “We could automate that.”

    Curious

    Good developers are often rather like Gregory House. They’re very easily bored by repetitive work (see laziness) and spend most of their time ploughing through it looking for an interesting and challenging (and hopefully new) problem to solve. The less time they can spend on the repetitive, the higher the frequency of the challenges.

    Curious developers will be constantly looking for new problems to solve, and better ways to solve previous problems. They’ll be the ones encouraging new ways to work and constantly tweaking and trying to improve existing systems. They’ll also be the ones most conscious of existing problems in the current working environment, and trying to correct those problems. Curious developers will usually have a wide breadth of knowledge, not just of their primary language(s), but of supportive, associated and alternative technologies.

    Curious (or easily-bored) developers are often the least stuck in their ways – the most open to change. They may well need convincing of why a new way of working is better (and that’s no bad thing) but as long as it’s an improvement, and likely to release more time to spend on the interesting problems, they’ll embrace it with a minimum of resistance.

    Curiosity also breeds creativity, another highly desirable trait in any developer. A strong desire to work out what has caused a problem and how to solve it is highly likely to motivate someone to continue once obvious avenues are exhausted. It is that sort of mentality that fosters “outside the box” thinking and creative coding.

    Possibly the most useful attribute of a curious developer is that desire to find and cure a problem rather than just paper over the crack.

    Likely to be heard saying: “Maybe there’s another way to do this.”

    Meticulous

    Many great developers are sticklers for detail. They will demand consistency in their work and the work of their team (they’re likely to care about common code standards and naming conventions, for example). They’ll want unit testing and peer review of code. They’ll want everyone in their team to comment on and document code. They are likely to be fussy about version control log messages.

    They’ll also be fussy about details in communication, and happy to ask what might seem like obvious questions, simply to be sure they have properly understood. This is especially true of things like bug reports. While they may not be terribly motivational communicators, they will usually be able to explain concepts clearly and effectively. That clarity is a tremendous advantage in any development environment, especially if teaching and learning are encouraged.

    Likely to be heard saying: “I just have a couple of questions …” I’m lazy, a little bit pessimistic, too much curious and meticulous: i’ll be a GREAT developer! soonn………..

    I think this is the best article to judge how great developer you are.This article is from ILoveJackDaniels.com.

    http://www.ilovejackdaniels.com/blog/what-makes-a-great-developer

    Filter Array into Categorized format
    January 23,2009 at 7:19 am | PHP | 1 Comment

    This simple yet powerful class to filters an array and breaks in to a categorized array format.You can use this class if you are dealing with large and complex array and want to convert it into and simple array that is easy to understand and use. Recently i required a function that can categorize an array and break it into categorize format.I couldn’t find any core function to do that so i decided to create my own class that can do this job for me. I have also added an example to demonstrate the usage to its benefit. Make sure you comment it if you find it useful.

    Original Array

     $arrProducts=array(
    array(
    "product_id" 			=> "007",
    "product_name"      	=> "Blackberry R-900 Mobile",
    "product_price" 		=> "£450",
    "product_status"		=>"1",
    "product_category"		=>"Mobile"
    ),
    array(
    "product_id" 			=> "033",
    "product_name"      	=> "8 GB Pendrive",
    "product_price" 		=> "£14.99",
    "product_status"		=> "0",
    "product_category"		=> "Computers"
    )
    );

    Array2ArrayTree Class

    Here is the class that converts the array to and organize format. The constructor take two arguments first the Array you want to format and the second category key you want to filter by.Then you have to call makeTree() function to format the array. The makeTree() function will return you the organized array.

    <?php
    /**
    * Array2ArrayTree
    * @package
    * @author Gaurav Jassal
    * @copyright http://www.gauravjassal.com
    * @version 1.0
    * @access public
    */
    class Array2ArrayTree
    {
    public $arrOriginal = array();
    public $arrDummy = array();
    public $strKey = "";
    /**
    * Array2ArrayTree::__construct()
    *
    * @param $arrData Array
    * @param $arrKey String
    * @return
    */
    public function __construct($arrData, $arrKey)
    {
    $this->arrOriginal = $arrData;
    $this->strKey = $arrKey;
    $this->arrDummy = array();
    }
    
    /**
    * Array2ArrayTree::makeTree()
    *
    * @return Array
    */
    public function makeTree()
    {
    for ($i = 0; $i <= sizeof($this->arrOriginal) - 1; $i++) {
    $keyPosition = $this->searchKey($this->arrOriginal[$i][$this->strKey]);
    if ($keyPosition == -1) {
    $this->addNode($this->arrOriginal[$i]);
    } else {
    $this->appendNode($this->arrOriginal[$i], $keyPosition);
    }
    }
    return $this->arrDummy;
    }
    /**
    * Array2ArrayTree::searchKey()
    *
    * @param $strCurrentValue String
    * @return
    */
    function searchKey($strCurrentValue)
    {
    for ($i = 0; $i <= sizeof($this->arrDummy) - 1; $i++) {
    if ($this->arrDummy[$i][0][$this->strKey] == $strCurrentValue) {
    return $i;
    }
    }
    return - 1;
    }
    /**
    * Array2ArrayTree::addNode()
    *
    * @param $arrNode Array
    * @return
    */
    function addNode($arrNode)
    {
    $this->arrDummy[sizeof($this->arrDummy)][0] = $arrNode;
    }
    /**
    * Array2ArrayTree::appendNode()
    *
    * @param $arrNode Array
    * @param $keyPosition Integer
    * @return
    */
    function appendNode($arrNode, $keyPosition)
    {
    array_push($this->arrDummy[$keyPosition], $arrNode);
    }
    }
    ?>

    Usage

    <?php
    require_once("array2arraytree.php");
    $arrProducts=array(
    array(
    "product_id" 			=> "007",
    "product_name"      	=> "Blackberry R-900 Mobile",
    "product_price" 		=> "£450",
    "product_status"		=>"1",
    "product_category"		=>"Mobile"
    ),
    array(
    "product_id" 			=> "033",
    "product_name"      	=> "8 GB Pendrive",
    "product_price" 		=> "£14.99",
    "product_status"		=> "0",
    "product_category"		=> "Computers"
    ),
    array(
    "product_id" 			=> "033",
    "product_name"      	=> "The White Tiger – Aravind Adiga",
    "product_price" 		=> "£29.99",
    "product_status"		=> "1",
    "product_category"		=> "Books"
    ),
    array(
    "product_id" 			=> "4501",
    "product_name"      	=> "The Final Reckoning - Sam Bourne",
    "product_price" 		=> "£19.99",
    "product_status"		=> "0",
    "product_category"		=> "Books"
    ),
    array(
    "product_id" 			=> "001",
    "product_name"      	=> "Wespro Multi-SIM &amp;amp;amp;amp; Touch-screen Mobile",
    "product_price" 		=> "£150",
    "product_status"		=> "1",
    "product_category"		=> "Mobile"
    ),
    array(
    "product_id" 			=> "004",
    "product_name"      	=> "Sigmatel MP4/MP3 + Camera Mobile",
    "product_price" 		=> "£150",
    "product_status"		=> "1",
    "product_category"		=> "Mobile"
    ),
    array(
    "product_id" 			=> "034",
    "product_name"      	=> "The Final Reckoning - Sam Bourne",
    "product_price" 		=> "£15.79",
    "product_status"		=> "0",
    "product_category"		=> "Books"
    ),
    array(
    "product_id" 			=> "334",
    "product_name"      	=> "250 GB Portable Hard Drive",
    "product_price" 		=> "£79.99",
    "product_status"		=> "1",
    "product_category"		=> "Computers"
    )
    );
    
    $objTree=new Array2ArrayTree($arrProducts,"product_category");
    $arrTree=$objTree->makeTree();
    print("
    ");
    print_r($arrTree);
    print("
    ");
    ?>

    Result Array

    Array
    (
    [0] => Array
    (
    [0] => Array
    (
    [product_id] => 007
    [product_name] => Blackberry R-900 Mobile
    [product_price] => £450
    [product_status] => 1
    [product_category] => Mobile
    )
    
    [1] => Array
    (
    [product_id] => 001
    [product_name] => Wespro Multi-SIM &amp;amp;amp;amp; Touch-screen Mobile
    [product_price] => £150
    [product_status] => 1
    [product_category] => Mobile
    )
    
    [2] => Array
    (
    [product_id] => 004
    [product_name] => Sigmatel MP4/MP3 + Camera Mobile
    [product_price] => £150
    [product_status] => 1
    [product_category] => Mobile
    )
    
    )
    
    [1] => Array
    (
    [0] => Array
    (
    [product_id] => 033
    [product_name] => 8 GB Pendrive
    [product_price] => £14.99
    [product_status] => 0
    [product_category] => Computers
    )
    
    [1] => Array
    (
    [product_id] => 334
    [product_name] => 250 GB Portable Hard Drive
    [product_price] => £79.99
    [product_status] => 1
    [product_category] => Computers
    )
    
    )
    
    [2] => Array
    (
    [0] => Array
    (
    [product_id] => 033
    [product_name] => The White Tiger – Aravind Adiga
    [product_price] => £29.99
    [product_status] => 1
    [product_category] => Books
    )
    
    [1] => Array
    (
    [product_id] => 4501
    [product_name] => The Final Reckoning - Sam Bourne
    [product_price] => £19.99
    [product_status] => 0
    [product_category] => Books
    )
    
    [2] => Array
    (
    [product_id] => 034
    [product_name] => The Final Reckoning - Sam Bourne
    [product_price] => £15.79
    [product_status] => 0
    [product_category] => Books
    )
    
    )
    
    )

    You can download the files here

    Recent Blog Entry

    Previously i posted a very useful class to categorize multi-dimensional array. I wrote another one that is just an alternative for array_unique function.


    Read More

    This extension notifies you with latest London underground tube updates. You can click on the browser button and check the status of any tube line.By default the extension updates the status in every 5 mins.


    Read More

    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

    Featured Projects

    My Blog

    © 2008 Gaurav Jassal