Skip to content

Instantly share code, notes, and snippets.

@jmoz
Created May 16, 2011 15:31
Show Gist options
  • Save jmoz/974654 to your computer and use it in GitHub Desktop.
Save jmoz/974654 to your computer and use it in GitHub Desktop.
Client observer
<?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);
}
}
}
@dol
Copy link

dol commented Jul 28, 2011

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.

@jmoz
Copy link
Author

jmoz commented Aug 25, 2011

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