0
0
PHPprogramming~30 mins

Observer pattern in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Observer pattern
📖 Scenario: You are building a simple notification system where a NewsPublisher sends news updates to multiple Subscribers. When the publisher has new news, all subscribers should be notified automatically.
🎯 Goal: Create a basic Observer pattern in PHP where a NewsPublisher notifies multiple Subscribers when news is published.
📋 What You'll Learn
Create a NewsPublisher class that holds news and a list of subscribers.
Create a Subscriber class that can receive news updates.
Implement methods to add subscribers to the publisher.
Notify all subscribers when new news is published.
Print the news received by each subscriber.
💡 Why This Matters
🌍 Real World
Observer pattern is used in real apps to update parts of a program automatically when something changes, like notifications, event handling, or UI updates.
💼 Career
Understanding Observer pattern helps in building scalable and maintainable software, especially in event-driven programming and frameworks.
Progress0 / 4 steps
1
Create the NewsPublisher class with a subscribers array
Create a class called NewsPublisher with a public property subscribers initialized as an empty array.
PHP
Need a hint?

Use public array $subscribers = []; inside the class to hold subscribers.

2
Create the Subscriber class with a name property
Create a class called Subscriber with a public property name. Add a constructor that accepts a string $name and sets the name property.
PHP
Need a hint?

Use public string $name; and a constructor to set it.

3
Add methods to NewsPublisher to add subscribers and notify them
In the NewsPublisher class, add a public method addSubscriber(Subscriber $subscriber) that adds the subscriber to the subscribers array. Also add a public method notifySubscribers(string $news) that loops over subscribers and calls a receiveNews(string $news) method on each subscriber.
PHP
Need a hint?

Use $this->subscribers[] = $subscriber; to add subscribers and a foreach loop to notify.

4
Create instances and test the notification system
Create a NewsPublisher instance called publisher. Create two Subscriber instances with names "Alice" and "Bob". Add both subscribers to publisher using addSubscriber. Call notifySubscribers on publisher with the news string "New PHP version released!". Print the output.
PHP
Need a hint?

Create objects and call methods exactly as described to see the notifications.