Complete the code to declare the Observer interface.
<?php
interface [1] {
public function update();
}
?>The Observer pattern requires an Observer interface that defines the update() method.
Complete the code to add an observer to the subject.
<?php class Subject { private $observers = []; public function [1](Observer $observer) { $this->observers[] = $observer; } } ?>
The method to add an observer is commonly named attach in PHP Observer implementations.
Fix the error in the notifyObservers method to call update on each observer.
<?php class Subject { private $observers = []; public function notifyObservers() { foreach ($this->observers as $observer) { $observer->[1](); } } } ?>
The update() method is the standard method called on observers to notify them of changes.
Fill both blanks to complete the observer class that implements the Observer interface.
<?php class ConcreteObserver implements [1] { public function [2]() { echo "Observer notified!"; } } ?>
The class must implement the Observer interface and define the update() method.
Fill all three blanks to complete the Subject class with attach, detach, and notify methods.
<?php class Subject { private $observers = []; public function [1](Observer $observer) { $this->observers[] = $observer; } public function [2](Observer $observer) { $index = array_search($observer, $this->observers, true); if ($index !== false) { unset($this->observers[$index]); } } public function [3]() { foreach ($this->observers as $observer) { $observer->update(); } } } ?>
The Subject class uses attach to add, detach to remove, and notifyObservers to notify all observers.