Bird
Raised Fist0
PHPprogramming~5 mins

Observer pattern in PHP

Choose your learning style10 modes available
Introduction

The Observer pattern helps objects talk to each other when something changes. It makes sure many parts can update automatically without being tightly connected.

You want to update multiple parts of a program when one part changes, like updating a display when data changes.
You want to keep parts of your program loosely connected so changes in one place don't break others.
You want to send notifications to many objects when an event happens, like sending alerts to users.
You want to separate the logic of what happens when data changes from the data itself.
Syntax
PHP
<?php
interface Observer {
    public function update(string $message): void;
}

interface Subject {
    public function attach(Observer $observer): void;
    public function detach(Observer $observer): void;
    public function notify(): void;
}

class ConcreteSubject implements Subject {
    private array $observers = [];
    private string $state = '';

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

    public function detach(Observer $observer): void {
        $this->observers = array_filter(
            $this->observers,
            fn($obs) => $obs !== $observer
        );
    }

    public function notify(): void {
        foreach ($this->observers as $observer) {
            $observer->update($this->state);
        }
    }

    public function setState(string $state): void {
        $this->state = $state;
        $this->notify();
    }
}

class ConcreteObserver implements Observer {
    private string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }

    public function update(string $message): void {
        echo "Observer {$this->name} received update: {$message}\n";
    }
}
?>

The Subject keeps a list of Observer objects and notifies them when needed.

Observers implement an update method to receive messages or data changes.

Examples
This example shows how to create a subject and two observers. When the subject state changes, both observers get notified.
PHP
<?php
// Create subject and observers
$subject = new ConcreteSubject();
$observer1 = new ConcreteObserver('A');
$observer2 = new ConcreteObserver('B');

// Attach observers
$subject->attach($observer1);
$subject->attach($observer2);

// Change state and notify observers
$subject->setState('Hello Observers!');
?>
Here, one observer is removed. Only the remaining observer receives the update.
PHP
<?php
// Detach an observer
$subject->detach($observer1);

// Change state again
$subject->setState('Second update');
?>
Sample Program

This program shows the Observer pattern in action. Two observers listen to the subject. When the subject changes, both get notified. Then one observer is removed, and only the remaining observer gets the next update.

PHP
<?php
interface Observer {
    public function update(string $message): void;
}

interface Subject {
    public function attach(Observer $observer): void;
    public function detach(Observer $observer): void;
    public function notify(): void;
}

class ConcreteSubject implements Subject {
    private array $observers = [];
    private string $state = '';

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

    public function detach(Observer $observer): void {
        $this->observers = array_filter(
            $this->observers,
            fn($obs) => $obs !== $observer
        );
    }

    public function notify(): void {
        foreach ($this->observers as $observer) {
            $observer->update($this->state);
        }
    }

    public function setState(string $state): void {
        $this->state = $state;
        $this->notify();
    }
}

class ConcreteObserver implements Observer {
    private string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }

    public function update(string $message): void {
        echo "Observer {$this->name} received update: {$message}\n";
    }
}

// Create subject and observers
$subject = new ConcreteSubject();
$observer1 = new ConcreteObserver('A');
$observer2 = new ConcreteObserver('B');

// Attach observers
$subject->attach($observer1);
$subject->attach($observer2);

// Change state and notify observers
$subject->setState('Hello Observers!');

// Detach one observer
$subject->detach($observer1);

// Change state again
$subject->setState('Second update');
?>
OutputSuccess
Important Notes

Make sure to detach observers when they no longer need updates to avoid memory leaks.

The pattern helps keep code organized and easy to change.

Summary

The Observer pattern lets objects watch and react to changes in another object.

It helps keep parts of your program loosely connected and easy to update.

Use it when many things need to know about changes in one place.

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

  1. Step 1: Understand the Observer pattern concept

    The Observer pattern is designed to let one object notify others about changes.
  2. 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.
  3. Final Answer:

    To allow objects to watch and react to changes in another object -> Option A
  4. 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

  1. Step 1: Recall the standard method to add observers

    In PHP's Observer pattern, the subject calls attach() to add observers.
  2. Step 2: Verify method and object roles

    The subject manages observers, so $subject->attach($observer); is correct.
  3. Final Answer:

    $subject->attach($observer); -> Option C
  4. Quick Check:

    Subject attaches observer = $subject->attach($observer) [OK]
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

  1. Step 1: Understand the flow of notification

    The subject changes state and notifies the observer, which prints the new state.
  2. Step 2: Identify the observer's reaction

    The observer prints the state 'Hello' when notified.
  3. Final Answer:

    Hello -> Option A
  4. 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

  1. Step 1: Check observer attachment before notify

    The code calls notify() without attaching any observers first.
  2. Step 2: Understand effect of no observers

    Since no observers are attached, notify() loops over an empty array and does nothing.
  3. Final Answer:

    No observers attached before notify is called -> Option D
  4. 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

  1. Step 1: Identify how to support multiple reactions

    Different observer classes allow each to react uniquely to the same notification.
  2. 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.
  3. Final Answer:

    Create different observer classes implementing a common interface and attach them to the subject -> Option B
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard