I'm not even sure is this is a "basic" bare-bones observer or if they've added fluffy bits to show off.
This is from phptr.com:
Code: Select all
<?php
interface Message
{
static function getType();
};
interface Observer
{
function notifyMsg(Message $msg);
};
class Subject
{
private $observers = array();
function registerObserver(Observer $observer, $msgType)
{
$this->observers[$msgType][] = $observer;
}
private function notifyMsg(Message $msg)
{
@$observers = $this->observers[$msg->getType()];
if(!$observers)
{
return;
}
foreach($observers as $observer)
{
$observer->notifyMsg($msg);
}
}
function someMethod()
{
//fake some task
sleep(1);
//notify observers
$this->notifyMsg(new HelloMessage("Zeev"));
}
}
class HelloMessage implements Message
{
private $name;
function __construct($name)
{
$this->name = $name;
}
function getMsg()
{
return "Hello, $this->name!";
}
static function getType()
{
return "HELLO_TYPE";
}
}
class MyObserver implements Observer
{
function notifyMsg(Message $msg)
{
if ($msg instanceof HelloMessage)
{
print $msg->getMsg();
}
}
}
$subject = new Subject();
$observer = new MyObserver();
$subject->registerObserver($observer,
HelloMessage::getType());
$subject->someMethod();
?>Code: Select all
Hello, Zeev!Can anybody enlighten me on these points?
a) Is this example the basics needed for the observer or have they added frilly bits?
b) Can anyone give a better example or describe a real situation where you'd use this?
Other examples I found online started off with lengthy unit tests which I know nothing about at the moment