Observer is a behavioral design pattern that allows one objects to notify other objects about changes in their state.
The Observer pattern provides a way to subscribe and unsubscribe to and from these events for any object that implements a subscriber interface.
Learn more about Observer
Application of the pattern in PHP
Usage examples: PHP has several built-in interfaces (SplSubject, SplObserver) that can be used to make your implementations of the Observer pattern compatible with the rest of the PHP code.
Example: Structure of the Pattern
This example illustrates the structure of the Observer design pattern and focuses on following questions:
- What classes does it consists of?
- What roles do these classes play?
- In what way the elements of the pattern are related?
After learning about the pattern’s structure it’ll be easier for you to grasp the following example, based on a real world PHP use case.
ObserverStructural.php: Structural Example
Example: Real World Example
In this example the Observer pattern allows various objects to observe events that are happening inside a user repository of an app.
The repository emits various types of events and allows observers to listen to all of them, as well as only individual ones.
ObserverRealWorld.php: Real world example