SplSubject

SplSubject is an SPL interface that represents the subject, also known as the observable, role in the Observer design pattern. Classes implementing SplSubject must define three methods: attach(SplObserver $observer), detach(SplObserver $observer), and notify().

When the subject’s state changes, it calls notify(), which in turn calls update() on each attached SplObserver.

SplSubject is the counterpart of SplObserver: together they provide a built-in, standardised contract for the Observer pattern.

<?php

    class EventSource implements SplSubject {
        private SplObjectStorage $observers;
        private string $state = '';

        public function __construct() {
            $this->observers = new SplObjectStorage();
        }

        public function attach(SplObserver $observer): void {
            $this->observers->attach($observer);
        }

        public function detach(SplObserver $observer): void {
            $this->observers->detach($observer);
        }

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

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

        public function getState(): string {
            return $this->state;
        }
    }

?>

Documentation

See also Observer pattern.

Related : Standard PHP Library (SPL), SplObserver, Observer Pattern, Interface, SplObjectStorage, Domain, Domain Name, DOMChildNode, DOMParentNode, Error Suppression, OAuth, Option, RandomCryptoSafeEngine, RandomEngine, RecursiveArrayIterator, RecursiveDirectoryIterator, Redirect, Reflector, SeekableIterator, Sequence, serialize_precision, Serverless, SessionHandlerInterface, SessionIdInterface, SessionUpdateTimestampHandlerInterface, Set, Shell Exec, SplFileInfo, PHP Native Interfaces

Added in PHP 5.1