- array_search: documentation ( source)
- rand: documentation ( source)
- printf: documentation ( source)
<?php
/** Object responsible for echoing debug data **/
class EchoLogger implements \SplObserver
{
public function update(\SplSubject $subject)
{
printf("Rand: %s, Status: %s", $subject->getRand(), $subject->getStatus());
}
}
/** Object responsible for emailing debug data **/
class EmailLogger implements \SplObserver
{
public function update(\SplSubject $subject)
{
/** Mail your data **/
}
}
class HttpClientService implements \SplSubject
{
private $observers = array();
public function getRand()
{
return $this->rand;
}
public function getStatus()
{
return $this->status;
}
public function attach(\SplObserver $observer)
{
$this->observers[] = $observer;
}
public function detach(\SplObserver $observer)
{
if($key = array_search($observer,$this->observers, true))
{
unset($this->observers[$key]);
}
}
public function notify()
{
foreach ($this->observers as $observer)
{
$observer->update($this);
}
}
public function getServiceStatus()
{
// -- SNIP --
$this->rand = rand(0, 10);
$this->status = ($this->rand >= 5) ? 'success' : 'error';
// -- Snip --
return $this->status;
}
}
$service = new HttpClientService;
$service->attach(new EchoLogger);
$service->getServiceStatus();