PHP
  Home arrow PHP arrow Page 2 - An Introduction to the Observer Pattern in PHP
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

An Introduction to the Observer Pattern in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 13
    2006-07-17


    Table of Contents:
  • An Introduction to the Observer Pattern in PHP
  • Building a practical example
  • Adding a basic error logger
  • Applying the Observer design pattern

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    An Introduction to the Observer Pattern in PHP - Building a practical example
    ( Page 2 of 4 )

    The introduction you read was aimed at providing you with an easy-to-grasp definition of the Observer pattern. As with many concepts related to PHP programming, things become clear only after satisfying the appetite for concrete code.

    In consonance with this, I’ll start with a simple example, which defines two classes that manipulate PHP strings. Take a look at the corresponding class definitions:

      // define 'MessageConverter' class
      class MessageConverter{
        private $message;
        public function __construct($message){
            if(!is_string($message)){
                throw new Exception('Input message must be a
    string!');
            }
            $this->message=strtoupper($message);
        }
        // return uppercased message
        public function getMessage(){
            return $this->message;
        }
      }
      // define 'MessageSaver' class
      class MessageSaver{
        const LENGTH_ERROR='Invalid length of message.';
        const WORD_ERROR='Message contains invalid words.';
        private $msgConv;
        private $msgPath='defaultPath/messages.txt';
        private $badWords=array('BAD WORD1','BAD WORD2','BAD WORD3');
        public function __construct(MessageConverter $msgConv){
            $this->msgConv=$msgConv;
        }
        public function save(){
            // check for message length
            if(strlen($this->msgConv->getMessage())>255){
                throw new Exception(self::LENGTH_ERROR);
            }
            // check for bad words
            if(in_array($this->msgConv->getMessage(),$this-
    >badWords)){
                throw new Exception(self::WORD_ERROR);
            }
            // checking was passed, then save message to file
            if(!$fp=fopen($this->msgPath,'a+')){
                throw new Exception('Error opening messages file.');
            }
            fwrite($fp,$this->msgConv->getMessage()."n");
            fclose($fp);
        }
      }

    As you can see, the two classes that I built above implement a simple mechanism that saves uppercased messages to a given text file. The first class, “MessageConverter,” is responsible for converting the input string passed as argument to uppercase, after which it returns the uppercased message to the calling code.

    Regarding the “MessageSaver” class, its functionality is really simple. It takes up objects of type “MessageConverter” and saves their messages to a text file, after checking whether the messages in question contain prohibited words or are of an inappropriate length. In both cases, the class will trigger the corresponding exceptions, notifying of the pertinent errors.

    Due to the simplicity of this example, let’s see how the above classes can be put to work quickly. Take a look at the following code snippet:

      try{
        // instantiate 'MessageConverter' object
        $msgConv=new MessageConverter('This message will be converted
    to uppercase!');
        // instantiate 'MessageSaver' object
        $msgSaver=new MessageSaver($msgConv);
        // save message to file
        $msgSaver->save();
      }
      catch(Exception $e){
        echo $e->getMessage();
        exit();
      }

    As shown above, the two classes seem to work seamlessly, and hopefully at the end of the script, the input message passed as a parameter will be saved in uppercase to the specified text file via the “save()” method. Also, it should be noted that these classes act like true independent components, since they have a well defined scope, and don’t overlap each other. What else can we ask for?

    Well, if you’re going to keep this trivial message-saving application untouched for a long time, then take a deep breathe and congratulate yourself for building such an efficient system. However, say you want to add some kind of error logging module to the application, to keep track of all the errors that will occur when offending messages are passed to the “MessageSaver” class. Sounds like a simple addition, right?

    In the next section I’ll show you how to add a basic error logger to the previous application, and hopefully you’ll see how the Observer pattern can be applied to solving some problems associated with the scope of the objects involved. Please keep on reading to learn more.



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek