Observer Pattern Examples

The Observer pattern is a software design pattern that is a good fit for situations where there is one thing that needs to send a message to many other things.

Said differently, it’s where one publisher updates one or many subscribers (or “observers”).

Here is a simple example

<?php

class Observer {
    function __construct($string) {
        $this->name = $string;
    }
    function update($string) {
        print $this->name . " received message: '" . $string . "'\n";
    }
}

class Publisher {
    private $subscribers = [];
    function add(Observer $observer) {
        array_push($this->subscribers, $observer);
    }
    function sendMessage($string) {
        foreach($this->subscribers as $key => $observer) {
            $observer->update($string);
        }
    }
}

$publisher = new Publisher();
$observer1 = new Observer("Observer 1");
$publisher->add($observer1);
$observer2 = new Observer("Observer 2");
$publisher->add($observer2);
$publisher->sendMessage("Hello!");

And the output looks like…

Observer 1 received message: 'Hello!'
Observer 2 received message: 'Hello!'

In the above example, we start by creating a Publisher object. Then create an Observer object, passing it a string “Observer 1” as it’s name. Then we pass the Observer object to the Publisher via the Publisher’s add() function. The add() function then pushes the Observer onto an array of $subscribers. Meaning that we’ve saved or “subscribed” the Observer.

We do it again with a second Observer object.

And now we have two Observers subscribed to the Publisher.

Then we call the sendMessage() function on the Publisher object (and pass it a message string “Hello!”), which loops through the array of $subscribers (Observers) and calls their update() function, passing it the message string.

And the result is each Observer prints it’s name and the message that was sent by the Publisher.

Nice!