PHP Classes

File: src/Observer/

Recommend this page to a friend!
  Classes of Ogbemudia Osayawe   Head First Design Patterns PHP   src/Observer/   Download  
File: src/Observer/
Role: Auxiliary data
Content type: text/markdown
Description: Auxiliary data
Class: Head First Design Patterns PHP
PHP version of the code examples of the book
Author: By
Last change:
Date: 3 years ago
Size: 1,139 bytes


Class file image Download

Observer pattern

Defines a one-to-many dependency between objects so that when one objects changes state, all its dependents get notified and updated automatically.

Design Principle

  • Identify the aspects of your application that vary and separate them from what stay the same
  • Program to an interface, not an implementation
  • Favor composition over inheritance
  • Strive for loosely coupled designs between objets that interacts


The example code is for Weather monitoring station

    use App\Observer\Weather\CurrentConditionDisplay;
    use App\Observer\Weather\ForcastDisplay;
    use App\Observer\Weather\WeatherData;

    $weatherData = new WeatherData();
    $currentConditionDisplay = new CurrentConditionDisplay($weatherData);
    $forcastDisplay          = new ForcastDisplay($weatherData);
    // both $currentConditionDisplay and $forcastDisplay get updated automatically
    $weatherData->changeMeasurements(35.9, 10.4, 20.2);
    // both $currentConditionDisplay and $forcastDisplay get updated automatically
    $weatherData->changeMeasurements(85.5, 19.4, 70.2);