observer design pattern

Observer Design Pattern (PHP)

Pius Adams Ijachi
4 min readJan 7, 2024

Hello, everyone! Welcome to my blog where I share my passion for coding and design patterns. Today, I’m going to talk about the Observer Pattern, what it is, when to use it, why it’s useful, and how to implement it in PHP. Let’s get started!

Laravel has a feature called events and listeners, which is similar to the observer pattern. Events and listeners allow you to trigger actions when a model or an object changes. For example, you can send an email when a user registers, or update a cache when a post is updated. Events are the messages that announce the change, and listeners are the classes that handle the events. Laravel observables are another way to implement the observer pattern, by attaching methods to models that run when certain events occur.

What is the Observer Pattern?

The Observer Pattern is a behavioral design pattern that defines a one-to-many relationship between objects. It allows an object, called the subject or observable, to notify other objects, called observers, about any changes in its state. The observers can then react accordingly to the update.

When to use the Observer Pattern?

The Observer Pattern is useful when you have a situation where:

  • You want to decouple the objects that produce data (observables) from the objects that consume data (observers).
  • You want to allow multiple observers to react to the same event or change in the observable.
  • You want to avoid polling or busy waiting for changes in the observable.

For example, you can use the Observer Pattern to implement a social media platform where users can post tweets and follow other users. The users who follow a user are the observers of that user’s tweets. Whenever the user posts a new tweet, the observable notifies all the observers about the new tweet. The observers can then display the tweet on their feeds or perform some other action.

Why is the Observer Pattern useful?

The Observer Pattern has several benefits, such as:

  • It promotes loose coupling between objects. The observables and observers only need to know about each other’s interfaces, not their internal details or implementations.
  • It allows for dynamic subscription and unsubscription of observers. The observables can add or remove observers at any time without affecting the rest of the system.
  • It supports broadcast communication. The observables can notify multiple observers at once with a single method call.

How to implement the Observer Pattern in PHP?

To implement the Observer Pattern in PHP, we need two interfaces: ObservableInterface and ObserversInterface. The ObservableInterface defines the methods that allow an object to register, remove, and notify observers. The ObserversInterface defines the method that allows an object to update itself when notified by an observable.

Here is an example of how these interfaces look like:

<?php
namespace Observer;interface ObservableInterface{    public function registerObserver(ObserversInterface $observer): void;    public function removeObserver(ObserversInterface $observer): void;    public function notifyObservers(): void;}interface ObserversInterface{    public function update(ObservableInterface $observable): void;}

Next, we need to create a concrete class that implements the ObservableInterface. This class will represent our user who can post tweets. We will call it UserTweets. This class will have an array of observers, a method to post a new tweet, a method to get the latest tweet, and the methods required by the ObservableInterface.

Here is what this class looks like:

<?php
namespace Observer;require_once 'ObservableInterface.php';require_once 'ObserversInterface.php';class UserTweets implements ObservableInterface{    protected array $observers = [];    public function newTweet(): void    {        $this->notifyObservers();    }    public function getTweet(): string    {        return "This is my first tweet";    }    public function registerObserver(ObserversInterface $observer): void    {        $this->observers[] = $observer;    }    public function removeObserver(ObserversInterface $observer): void    {        $index = array_search($observer, $this->observers);        if ($index){            unset($this->observers[$index]);        }    }    public function notifyObservers(): void    {        foreach ($this->observers as $observer){            $observer->update($this);        }    }}

Finally, we need to create a concrete class that implements the ObserversInterface. This class will represent our user who can follow other users and see their tweets. We will call it UserFollows. This class will have a method to display the tweet of the user it follows and the method required by the ObserversInterface.

Here is what this class looks like:

<?php
namespace Observer;require_once 'ObservableInterface.php';require_once 'ObserversInterface.php';class UserFollows implements ObserversInterface{    public function update(ObservableInterface $observable): void    {        echo "New tweet from " . get_class($observable) . ": " . $observable->getTweet() . "\n";    }}

Now, we can test our implementation by creating some instances of UserTweets and UserFollows and registering them as observers.

Here is an example of how we can do that:

<?php
require_once 'UserTweets.php';require_once 'UserFollows.php';use Observer\UserTweets;use Observer\UserFollows;$user1 = new UserTweets();$user2 = new UserFollows();$user3 = new UserFollows();$user1->registerObserver($user2);$user1->registerObserver($user3);$user1->newTweet();The output of this code will be:New tweet from Observer\UserTweets: This is my first tweetNew tweet from Observer\UserTweets: This is my first tweet

As you can see, the UserTweets class notifies the UserFollows classes about its new tweet, and the UserFollows classes display the tweet on their feeds.

That’s it for today’s blog post. You can find the code here

--

--

Pius Adams Ijachi
Pius Adams Ijachi

No responses yet