📖 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
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
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
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
Hint
Create objects and call methods exactly as described to see the notifications.
Practice
(1/5)
1. What is the main purpose of the Observer pattern in PHP programming?
easy
A. To allow objects to watch and react to changes in another object
B. To speed up the execution of PHP scripts
C. To store data in a database efficiently
D. To handle user input validation
Solution
Step 1: Understand the Observer pattern concept
The Observer pattern is designed to let one object notify others about changes.
Step 2: Match the purpose with the options
To allow objects to watch and react to changes in another object correctly describes this notification and reaction mechanism.
Final Answer:
To allow objects to watch and react to changes in another object -> Option A
Quick Check:
Observer pattern = objects watch and react [OK]
Hint: Observer pattern = watch and react to changes [OK]
Common Mistakes:
Confusing Observer with database or input handling
Thinking it speeds up code execution
Mixing it with unrelated design patterns
2. Which of the following is the correct way to attach an observer to a subject in PHP using the Observer pattern?
easy
A. $subject->addObserver($observer);
B. $observer->attach($subject);
C. $subject->attach($observer);
D. $observer->addSubject($subject);
Solution
Step 1: Recall the standard method to add observers
In PHP's Observer pattern, the subject calls attach() to add observers.
Step 2: Verify method and object roles
The subject manages observers, so $subject->attach($observer); is correct.
Hint: Subject attaches observer with attach() method [OK]
Common Mistakes:
Calling attach() on observer instead of subject
Using non-standard method names like addObserver
Mixing up subject and observer roles
3. Given the following PHP code using the Observer pattern, what will be the output?
$subject = new Subject();
$observer = new ConcreteObserver();
$subject->attach($observer);
$subject->setState('Hello');
Assuming ConcreteObserver prints the new state when notified.
medium
A. Hello
B. State changed
C. No output
D. Error: method not found
Solution
Step 1: Understand the flow of notification
The subject changes state and notifies the observer, which prints the new state.
Step 2: Identify the observer's reaction
The observer prints the state 'Hello' when notified.
Final Answer:
Hello -> Option A
Quick Check:
Observer prints new state = Hello [OK]
Hint: Observer prints state when notified after attach [OK]
Common Mistakes:
Assuming no output without calling notify explicitly
Confusing printed message with generic text
Expecting errors without method definitions
4. What is wrong with this PHP Observer pattern code snippet?
class Subject {
private $observers = [];
public function attach($observer) {
$this->observers[] = $observer;
}
public function notify() {
foreach ($this->observers as $observer) {
$observer->update();
}
}
}
$subject = new Subject();
$subject->notify();
medium
A. attach() method is missing
B. Observers array is private and inaccessible
C. notify() method should not call update()
D. No observers attached before notify is called
Solution
Step 1: Check observer attachment before notify
The code calls notify() without attaching any observers first.
Step 2: Understand effect of no observers
Since no observers are attached, notify() loops over an empty array and does nothing.
Final Answer:
No observers attached before notify is called -> Option D
Quick Check:
Notify without observers = no action [OK]
Hint: Attach observers before notify() to trigger updates [OK]
Common Mistakes:
Thinking private array causes error
Assuming attach() method is missing
Believing notify() should not call update()
5. You want to implement an Observer pattern in PHP where multiple observers react differently to the same state change. Which approach best supports this requirement?
hard
A. Use a single observer class and change its behavior with if-else inside update()
B. Create different observer classes implementing a common interface and attach them to the subject
C. Attach only one observer and switch its internal state manually
D. Avoid using Observer pattern and use global variables instead
Solution
Step 1: Identify how to support multiple reactions
Different observer classes allow each to react uniquely to the same notification.
Step 2: Evaluate options for flexibility and design
Create different observer classes implementing a common interface and attach them to the subject uses a common interface but different classes, which is clean and scalable.
Final Answer:
Create different observer classes implementing a common interface and attach them to the subject -> Option B
Quick Check:
Multiple observers = different classes with common interface [OK]
Hint: Use multiple observer classes for different reactions [OK]
Common Mistakes:
Using one observer with complex if-else logic
Attaching only one observer limits reactions
Ignoring design principles by using globals
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.