PHP
  Home arrow PHP arrow Page 2 - An Introduction to the Observer Patter...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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? 
PHP

An Introduction to the Observer Pattern in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 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:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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


       · If you're a PHP developer that wishes to learn how to implement the observer pattern...
     

       

    PHP ARTICLES

    - Using Aliases and the Autoload Function with...
    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Sub Classing Exceptions in PHP 5
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...

     
    Application Delivery: Everything You Wanted to Know, but Didn`t Know You Needed to Ask
    A comprehensive guide to examining the topics of Wide-area Data Services and app....

     
    Best Practices: Safe and Secure Hardware Asset Recovery
    Companies increasingly must meet EPA and local requirements for the disposal of ....

     
    Managing SSL Security in Multi-Server Environments
    Read this white paper to learn how to simplify management of your organization's....

     
    Open Source Security Myths
    Open Source Software (OSS) is computer software whose source code is available t....

     
    Power and Cooling Capacity Management for Data Centers
    This paper describes the principles for achieving power and cooling capacity man....

     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT