PHP › Design Patterns in PHP
How does the Observer pattern let objects react automatically to events occurring in another object, and where is this pattern commonly used in PHP applications?
IntermediateAnswer
The Observer pattern lets an object, called the subject, maintain a list of dependent objects, called observers, and automatically notify all of them whenever a significant event or state change occurs, and this pattern commonly appears in PHP applications through event dispatcher systems provided by frameworks like Laravel and Symfony, letting different parts of an application react to events like a user registering, without those different parts needing direct knowledge of each other.
$dispatcher->addListener('user.registered', function ($event) {
sendWelcomeEmail($event->user);
});
$dispatcher->dispatch('user.registered', new UserRegisteredEvent($user));Real-world example A user registration system dispatches a user registered event, and completely separate parts of the application, such as sending a welcome email and creating a default user preferences record, react to that single event independently without any direct coupling between them.