0
0
PHPprogramming~10 mins

Observer pattern in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare the Observer interface.

PHP
<?php
interface [1] {
    public function update();
}
?>
Drag options to blanks, or click blank then click option'
AObservable
BListener
CSubject
DObserver
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Subject' instead of 'Observer' as interface name.
Naming the interface 'Listener' which is not standard here.
2fill in blank
medium

Complete the code to add an observer to the subject.

PHP
<?php
class Subject {
    private $observers = [];

    public function [1](Observer $observer) {
        $this->observers[] = $observer;
    }
}
?>
Drag options to blanks, or click blank then click option'
Aattach
BaddObserver
CregisterObserver
Dadd
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'addObserver' which is common in other languages but not here.
Using 'add' which is too generic.
3fill in blank
hard

Fix the error in the notifyObservers method to call update on each observer.

PHP
<?php
class Subject {
    private $observers = [];

    public function notifyObservers() {
        foreach ($this->observers as $observer) {
            $observer->[1]();
        }
    }
}
?>
Drag options to blanks, or click blank then click option'
Anotify
Bupdate
Crefresh
Dcall
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a non-existent method like 'notify' or 'refresh'.
Using 'call' which is not a method name.
4fill in blank
hard

Fill both blanks to complete the observer class that implements the Observer interface.

PHP
<?php
class ConcreteObserver implements [1] {
    public function [2]() {
        echo "Observer notified!";
    }
}
?>
Drag options to blanks, or click blank then click option'
AObserver
BSubject
Cupdate
Dnotify
Attempts:
3 left
💡 Hint
Common Mistakes
Implementing 'Subject' instead of 'Observer'.
Naming the method 'notify' instead of 'update'.
5fill in blank
hard

Fill all three blanks to complete the Subject class with attach, detach, and notify methods.

PHP
<?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();
        }
    }
}
?>
Drag options to blanks, or click blank then click option'
Aattach
Bdetach
CnotifyObservers
DremoveObserver
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'addObserver' or 'removeObserver' instead of 'attach' and 'detach'.
Naming notify method simply 'notify' instead of 'notifyObservers'.