The Observer Pattern with SPL Interfaces
The Observer design pattern is a behavioral pattern where an object (the subject) maintains a list of its dependents (observers) and notifies them automatically of any state changes. PHP provides built-in support for this pattern through two specific interfaces: SplSubject and SplObserver.
To implement this pattern, a class must implement SplSubject to manage the lifecycle of its listeners. This requires the implementation of three specific methods: attach() to add an observer, detach() to remove one, and notify() to broadcast updates. Conversely, any class that wishes to receive these updates must implement SplObserver, which requires a single update() method to receive the subject instance.
<?php
/**
* The Subject class manages a list of observers and notifies them
* when its internal state changes.
*/
class DataStore implements SplSubject
{
private array $observers = [];
private string $data = '';
// Attach an observer to the list
public function attach(SplObserver $observer): void
{
$this->observers[] = $observer;
}
// Detach an observer from the list
public function detach(SplObserver $observer): void
{
$key = array_search($observer, $this->observers, true);
if ($key !== false) {
unset($this->observers[$key]);
}
}
// Notify all attached observers by calling their update() method
public function notify(): void
{
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
// Business logic that triggers a notification
public function setData(string $data): void
{
$this->data = $data;
$this->notify();
}
public function getData(): string
{
return $this->data;
}
}
/**
* The Observer class reacts to updates from the subject.
*/
class Logger implements SplObserver
{
private string $name;
public function __construct(string $name)
{
$this->name = $name;
}
// Receive the update from the subject
public function update(SplSubject $subject): void
{
// We check if the subject is our specific DataStore to access its data
if ($subject instanceof DataStore) {
echo "[{$this->name}] Data changed to: " . $subject->getData() . PHP_EOL;
}
}
}
// --- Execution Example ---
$store = new DataStore();
$loggerA = new Logger('LoggerA');
$loggerB = new Logger('LoggerB');
// Registering observers
$store->attach($loggerA);
$store->attach($loggerB);
// Triggers update() in both LoggerA and LoggerB
$store->setData('Initial State');
// Detach LoggerA
$store->detach($loggerA);
// Triggers update() only in LoggerB
$store->setData('Updated State');Key Implementation Details
When implementing these interfaces, keep the following technical requirements in mind:
Method Signatures: The implementing class must declare all methods from the interface with a compatible signature. While parameter names can differ, it is recommended to keep them consistent for clarity and compatibility with PHP named arguments.
Public Visibility: All methods declared in an interface must be public.
Subject Management: In this specific example, the detach() method uses array_search with strict comparison to ensure the correct observer instance is removed. Note that the array-based attach() implementation used here permits duplicate registrations.
Type Checking: Inside the SplObserver::update() method, it is common practice to use instanceof to verify the subject's type. This allows the observer to safely access specific methods of the subject (like getData()) that are not part of the generic SplSubject interface.
Limitations
This implementation focuses on the standard method contracts for SplSubject and SplObserver. It does not address advanced PHP features such as interface property declarations (available in PHP 8.4+) or complex variance rules (covariance and contravariance) for method return types and parameters. Note that the example uses typed properties, which require PHP 7.4 or higher.
Expected Output
Based on the provided code example, the execution will produce the following output:
[LoggerA] Data changed to: Initial State
[LoggerB] Data changed to: Initial State
[LoggerB] Data changed to: Updated StatePHP interfaces define the 'what' (the method signatures), while the implementing classes define the 'how' (the logic). Using SplSubject and SplObserver provides a standardized way to implement the Observer pattern, ensuring that subjects and observers can interact through a predictable contract.