Implementing the Observer Pattern in PHP

Introduction to the Observer Pattern in PHP

Welcome back! We're continuing our exploration of Behavioral Patterns. In this lesson, we will delve into the Observer Pattern, a critical design pattern that emphasizes object communication and responsibility distribution. This pattern allows an object, known as the subject, to maintain a list of its dependents, called observers, and automatically notify them of any state changes.

We previously explored the Command Pattern in PHP, which encapsulates a request as an object. Now, let's build on that knowledge and discover how the Observer Pattern facilitates seamless and efficient communication between objects.

What You'll Learn

In this lesson, you will learn how to implement the Observer Pattern by understanding its main components and roles. We'll break down the pattern into manageable parts and demonstrate its practical use with clear PHP examples.

Here's a simple illustration to get you started:

We start by defining a NewsPublisher class that maintains a list of subscribers. When new news is published, the NewsPublisher notifies all subscribers by calling their update method. Each Subscriber can then process the news as needed.

Code Example: Defining the News Publisher Class

PHP
class NewsPublisher {
    private $subscribers = [];

    public function addSubscriber(Subscriber $subscriber) {
        $this->subscribers[] = $subscriber;
    }

    public function removeSubscriber(Subscriber $subscriber) {
        $this->subscribers = array_filter($this->subscribers, function ($sub) use ($subscriber) {
            return $sub !== $subscriber;
        });
    }

    public function publish($news) {
        foreach ($this->subscribers as $subscriber) {
            $subscriber->update($news);
        }
    }
}

Code Example: Defining the Subscriber Interface and Concrete Implementation

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal