observer.php
function autoloader($class) {
$newName = str_replace('\\', '/', $class);
$path = "lib/$newName.php";
if (!class_exists($class)) {
if (file_exists($path)) {
require $path;
}
}
}
spl_autoload_register(autoloader);
ini_set('display_errors', true);
$alarmAnlage = new \Alarm\System();
$alarmAnlage->attach(new \Alarm\Observer\Email());
$alarmAnlage->attach(new \Alarm\Observer\SMS());
$alarmAnlage->attach(new \Alarm\Observer\Telefon());
$alarmAnlage->triggerAlert("Klimaanlage ausgefallen");
lib/Alarm/Observer.php
namespace Alarm;
abstract class Observer {
abstract public function update(System $system);
}
lib/Alarm/System.php
namespace Alarm;
interface AlarmDispatcher {
public function attach(Observer $observer);
public function detach(Observer $observer);
public function notify();
}
class System implements AlarmDispatcher
{
private $_alertMsg = "";
private $_observers = array();
public function triggerAlert(string $msg)
{
$this->_alertMsg = $msg;
$this->notify();
}
public function getAlert() {
return $this->_alertMsg;
}
public function attach(Observer $observer)
{
$this->_observers[] = $observer;
}
public function detach(Observer $observer)
{
foreach ($this->_observers as $index => $currentObserver) {
if ($observer == $currentObserver) {
unset($this->_observers[$index]);
}
}
}
public function notify()
{
foreach ($this->_observers as $observer) {
$observer->update($this);
}
}
}
Observer
lib/Alarm/Observer/Email.php
namespace Alarm\Observer;
use Alarm\Observer;
use Alarm\System;
class Email extends Observer {
public function update(System $system)
{
printf("E-Mail Alarm: %s<br>", $system->getAlert());
}
}
lib/Alarm/Observer/SMS.php
namespace Alarm\Observer;
use Alarm\Observer;
use Alarm\System;
class SMS extends Observer {
public function update(System $system)
{
printf("SMS Alarm: %s<br>", $system->getAlert());
}
}
lib/Alarm/Observer/Telefon.php
namespace Alarm\Observer;
use Alarm\Observer;
use Alarm\System;
class Telefon extends Observer {
public function update(System $system)
{
printf("Telefonanruf: %s<br>", $system->getAlert());
}
}