Skip to content

Instantly share code, notes, and snippets.

@jmoz
Created May 16, 2011 15:31
Show Gist options
  • Select an option

  • Save jmoz/974654 to your computer and use it in GitHub Desktop.

Select an option

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);
}
}
}
@jmoz

jmoz commented Aug 25, 2011

Copy link
Copy Markdown
Author

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