Home arrow PHP arrow Page 2 - An Introduction to the Observer Pattern in PHP

Building a practical example - PHP

If you have reached the point in your programming life where you are using design patterns, you will want to read this article. The first of a three-part series, it covers the Observer pattern, which can be just the thing for situations where objects need to send information to a centralized mechanism.

  1. An Introduction to the Observer Pattern in PHP
  2. Building a practical example
  3. Adding a basic error logger
  4. Applying the Observer design pattern
By: Alejandro Gervasio
Rating: starstarstarstarstar / 15
July 17, 2006

print this article



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){
            throw new Exception('Input message must be a
    // 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){
    public function save(){
        // check for message length
            throw new Exception(self::LENGTH_ERROR);
        // check for bad words
            throw new Exception(self::WORD_ERROR);
        // checking was passed, then save message to file
            throw new Exception('Error opening messages file.');

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:

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

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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: