Created
May 16, 2011 15:31
-
-
Save jmoz/974654 to your computer and use it in GitHub Desktop.
Client observer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ServiceClient implements SplSubject { | |
private $service; | |
private $http; | |
private $observers; | |
public function __construct(Service $service, Http $http) { | |
$this->service = $service; | |
$this->http = $http; | |
} | |
public function getService() { | |
return $this->service; | |
} | |
public function setService(Service $service) { | |
$this->service = $service; | |
} | |
public function call() { | |
$this->http->setUrl($this->service->getUrl()); | |
$this->http->setMethod($this->service->getMethod()); | |
$this->http->setBody($this->service->getBody()); | |
$this->http->send(); | |
$this->notify(); | |
return $this->http->getResponseBody(); | |
} | |
public function attach(SplObserver $observer) { | |
$this->observers[spl_object_hash($observer)] = $observer; | |
} | |
public function detach(SplObserver $observer) { | |
unset($this->observers[spl_object_hash($observer)]); | |
} | |
private function notify() { | |
foreach ($this->observers as $observer) { | |
$observer->update($this); | |
} | |
} | |
} |
In the example the call to the logging method was at that point, that is why I left the notify() call in the same place. However you are completely right, the later on we put the call to notify(), the more information is available to the observer. I've updated the example, thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why is the $this->notify() sent befor the manipulation of $this->http is made? The observer will be notified with the non manipulated object. If call() is called the second time, $this->http has an old state.
IMHO is the example missleading that notify() has to be triggered befor an certain event. Is the observer pattern not used to inform about certain events that happend evaluating the code.