Implementing a Notification System Using the Observer Pattern in PHP

Implementing a Notification System Using the Observer Pattern in PHP

On5th Nov 2024, 2024-12-04T09:52:41+05:30 ByKarthik Kumar D K | read
Listen Pause Resume Stop

The Observer pattern is a powerful design pattern that promotes a one-to-many dependency between objects. This pattern is particularly useful in scenarios where changes in one object need to be reflected across multiple objects. A classic use case for the Observer pattern is in building a notification system, where subscribers (observers) are notified of changes in a publisher (subject).

In this article, we'll explore how to implement a simple notification system using the Observer pattern in PHP 8.

Understanding the Observer Pattern

In the Observer pattern:

  • Subject: The object that maintains a list of observers and notifies them of changes.
  • Observer: The object that wants to be notified of changes in the subject.

Key Features:

  • Loose coupling between the subject and observers.
  • Dynamic subscription and unsubscription of observers.
  • Supports multiple observers for a single subject.

Implementing the Notification System

Let’s build a notification system step by step.

Step 1: Define the Observer Interface

First, we need an interface that all observers will implement. This interface will define the method that observers must implement to receive notifications.

interface Observer {

    public function update(string $message): void;

}

Step 2: Create the Subject Class

Next, we implement the subject class. This class will manage the list of observers and provide methods to attach, detach, and notify observers.

class NotificationService {

    private array $observers = [];

    public function attach(Observer $observer): void {

        $this->observers[] = $observer;

    }

    public function detach(Observer $observer): void {

        $this->observers = array_filter($this->observers, fn($obs) => $obs !== $observer);

    }

    public function notify(string $message): void {

        foreach ($this->observers as $observer) {

            $observer->update($message);

        }

    }

}

Step 3: Create Concrete Observer Classes

Now, let’s create some concrete observer classes that implement the Observer interface. These classes will define what to do when they receive notifications.

class EmailNotifier implements Observer {

    public function update(string $message): void {

        echo "Email Notification: $message\n";

    }

}

class SmsNotifier implements Observer {

    public function update(string $message): void {

        echo "SMS Notification: $message\n";

    }

}

class AppNotifier implements Observer {

    public function update(string $message): void {

        echo "App Notification: $message\n";

    }

}

Step 4: Putting It All Together

Now, we can use our NotificationService along with the observer classes to send notifications.

// Create the notification service

$notificationService = new NotificationService();

// Create observers

$emailNotifier = new EmailNotifier();

$smsNotifier = new SmsNotifier();

$appNotifier = new AppNotifier();

// Attach observers

$notificationService->attach($emailNotifier);

$notificationService->attach($smsNotifier);

$notificationService->attach($appNotifier);

// Send notifications

$notificationService->notify("A new update is available!");

Step 5: Detach Observers (Optional)

If you want to remove observers dynamically, you can use the detach method. Here’s how:

// Detach SMS notifier

$notificationService->detach($smsNotifier);

// This will only notify Email and App observers

$notificationService->notify("Another important update!");

Conclusion

Using the Observer pattern to implement a notification system in PHP 8 allows for a clean, maintainable, and scalable architecture. It decouples the components, making it easy to add or remove observers without affecting the subject. This pattern is widely applicable in various scenarios, from user interfaces to event-driven systems.

As you develop more complex applications, consider the Observer pattern as a way to manage notifications effectively, ensuring your system remains responsive and flexible to changes.

Thanks for reading the article, for more Science & Technology related articles read and subscribe to peoples blog articles.

Labels


Related Articles

17% OFF
iQOO 12 5G (Legend, 12GB RAM, 256GB Storage)

iQOO 12 5G (Legend, 12GB RAM, 256GB Storage)

49,999 59,999

Recent Articles

Recent Quick Read

Recent Great People

We Need Your Consent
By clicking “Accept Cookies”, you agree to the storing of cookies on your device to enhance your site navigation experience.
I Accept Cookies