Skip to content

Instantly share code, notes, and snippets.

@phpfour
Created February 3, 2013 18:44
Show Gist options
  • Save phpfour/4703079 to your computer and use it in GitHub Desktop.
Save phpfour/4703079 to your computer and use it in GitHub Desktop.
A simple observer implementation.
<?php
interface Observable
{
public function callback($event, $value);
}
class WeatherDashboard implements Observable
{
private $temperature;
private $airSpeed;
public function showStats()
{
echo "Current Temperature : ", $this->temperature, PHP_EOL;
echo "Current Air Speed : ", $this->airSpeed, PHP_EOL;
}
public function callback($event, $value)
{
if ($event == "temperature-change") {
$this->temperature = $value;
}
if ($event == "airspeed-change") {
$this->airSpeed = $value;
}
}
}
class TemperatureMonitor
{
private $temp;
private $dispatcher;
public function __construct($dispatcher)
{
$this->dispatcher = $dispatcher;
}
public function getTemperature()
{
return $this->temp;
}
public function setTemperature($temp)
{
$this->temp = $temp;
$this->dispatcher->notify("temperature-change", $temp);
}
}
class AirSpeedMonitor
{
private $speed;
private $dispatcher;
public function __construct($dispatcher)
{
$this->dispatcher = $dispatcher;
}
public function getAirSpeed()
{
return $this->speed;
}
public function setAirSpeed($speed)
{
$this->speed = $speed;
$this->dispatcher->notify("airspeed-change", $speed);
}
}
class Dispatcher
{
private $observers;
public function register($event, Observable $observer)
{
$this->observers[] = array($event => $observer);
}
public function notify($event, $value)
{
echo "Got notified about event: $event with value: $value", PHP_EOL;
foreach ($this->observers as $key => $observers) {
foreach ($observers as $observer) {
$observer->callback($event, $value);
}
}
}
}
$wd = new WeatherDashboard();
$wd->showStats();
$dis = new Dispatcher();
$dis->register("temperature-change", $wd);
$dis->register("airspeed-change", $wd);
$tm = new TemperatureMonitor($dis);
$tm->setTemperature("10 c");
$asm = new AirSpeedMonitor($dis);
$asm->setAirSpeed("30 knot");
$wd->showStats();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment