How does the Observer Pattern compare to using static methods for dependency injection in PHP?
Using the Observer Pattern allows for loosely coupled communication between objects by having one object (the subject) maintain a list of dependents (observers) that are notified of any changes. This promotes better separation of concerns and makes it easier to add or remove observers without modifying the subject. On the other hand, using static methods for dependency injection can lead to tight coupling and make it harder to test and maintain the code.
// Observer Pattern implementation
interface Subject {
public function attach(Observer $observer);
public function detach(Observer $observer);
public function notify();
}
interface Observer {
public function update();
}
class ConcreteSubject implements Subject {
private $observers = [];
public function attach(Observer $observer) {
$this->observers[] = $observer;
}
public function detach(Observer $observer) {
$key = array_search($observer, $this->observers);
if ($key !== false) {
unset($this->observers[$key]);
}
}
public function notify() {
foreach ($this->observers as $observer) {
$observer->update();
}
}
}
class ConcreteObserver implements Observer {
public function update() {
echo "Observer notified of change\n";
}
}
$subject = new ConcreteSubject();
$observer = new ConcreteObserver();
$subject->attach($observer);
$subject->notify();
Related questions
-
file upload directory permissions PHP configuration
-
PHP tags template system syntax
-
PHP CSS HTML