Sobes.tech
Junior — Middle

Have you applied the 'Observer' pattern in your projects?

sobes.tech AI

Answer from AI

Yes, the "Observer" pattern was used in PHP projects to implement an event-driven model, where one object (the subject) notifies many other objects (observers) about changes in its state.

Example of usage in PHP:

interface Observer {
    public function update(string $eventData);
}

class Subject {
    private $observers = [];

    public function attach(Observer $observer) {
        $this->observers[] = $observer;
    }

    public function notify(string $eventData) {
        foreach ($this->observers as $observer) {
            $observer->update($eventData);
        }
    }

    public function changeState() {
        // Change state
        $this->notify('State changed');
    }
}

class ConcreteObserver implements Observer {
    public function update(string $eventData) {
        echo "Received notification: $eventData\n";
    }
}

$subject = new Subject();
$observer = new ConcreteObserver();
$subject->attach($observer);
$subject->changeState();

This approach helps separate the logic of changing state from reacting to these changes, improving the extensibility and maintainability of the code.