How to implement Observer Pattern in PHP?

What is Observer Pattern?

The Observer Pattern is the behavioral software design pattern in which an object (act as a subject) keeps a list of dependents (known as observers) and notifies them whenever there is a change in its state. It is also known as Publisher-Subscriber pattern since observers are subscribing to the subject or publisher.

In the model-view-controller (MVC) framework, Observer Pattern is used for implementing the view part.

According to the Gang of Four (GoF), the intent of the Observer pattern is to “Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. So, In a nutshell, it provides a way to handle the notifications automatically.

So, when do we need it?

  • If there are multiple objects or actions that are dependent on some event. Like in server monitoring system, If some service fails, it needs to notify all the dependent services. Another example could be the message queues, where a queue manager needs to notify all the queue listeners on arriving a new message.
  • If we need a dynamic solution where a system or object can subscribe or unsubscribe a particular system or channel on fly. Like the Blog Newsletters, As a user you can subscribe or un-subscribe. So, If you have subscribed, you will get to know about all latest posts and releases otherwise you manually need to check the updates.

How to implement Observer Pattern in PHP?

Lets take an example of Blog Newsletter, mentioned above. In this example Blog is our Subject and Reader is the Observer or Subscriber.

There are four Key components involved:

  1. Subject Interface
  2. Observer Interface
  3. Subject (Blog) Implementation
  4. Observer (Reader) Implementation

Now, let’s have a look at each of them.

Subject Interface

Subject needs to implement a Subject Interface having three methods attach, detach and notify

Observer Interface

Observer needs to implement Observer Interface having only one methods update

If we are running PHP >= 5.1 then we can also use Standard PHP Library (SPL) provided splObserver and splSubject interfaces.

Subject (Blog) Implementation

Observer (Reader) Implementation

Everything together

Lets see the whole stuff together.

Here is the output of the above run:

Thats all about the Observer Pattern, Please let me know your thoughts and feedback in comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *