Created
November 2, 2009 18:37
-
-
Save till/224332 to your computer and use it in GitHub Desktop.
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 | |
require_once 'HTTP/Request2.php'; | |
class ArmChair extends HTTP_Request2 | |
{ | |
protected $server; | |
public function __construct($server) | |
{ | |
$this->server = $server; | |
parent::__construct($server); | |
} | |
public function get($id = null) | |
{ | |
if ($id === null) { | |
$this->setUri($this->server . '/_all_docs') | |
} else { | |
$id = urlencode($id); | |
$this->setUri($this->server . '/' . $id); | |
} | |
$this->setMethod(HTTP_Request2::METHOD_GET); | |
$response = $this->send(); | |
return $this->parseResponse($response); | |
} | |
public function addDocument(array $data) | |
{ | |
if (isset($data['_id'])) { | |
$id = urlencode($data['_id']); | |
unset($data['_id']); | |
$this->setUri($this->server . '/' . $id); | |
$this->setMethod(HTTP_Request2::METHOD_PUT); | |
} else { | |
$this->setUri($this->server); | |
$this->setMethod(HTTP_Request2::METHOD_POST); | |
} | |
$this->setBody(json_encode($data)); | |
$response = $this->send(); | |
return $this->parseResponse($response); | |
} | |
public function deleteDocument($id) | |
{ | |
$id = urlencode($id); | |
$this->setUri($this->server . '/' . $id); | |
$this->setMethod(HTTP_Request2::METHOD_DELETE); | |
$response = $this->send(); | |
return $this->parseResponse($response); | |
} | |
public function updateDocument($id, $data) | |
{ | |
$id = urlencode($id); | |
$this->setUri($this->server . '/' . $id); | |
$this->setMethod(HTTP_Request2::METHOD_POST); | |
$this->setBody(json_encode($data)); | |
$response = $this->send(); | |
return $this->parseResponse($response); | |
} | |
protected function parseResponse(HTTP_Request2_Response $response) | |
{ | |
return json_decode($response->getBody()); | |
} | |
} | |
// example | |
$armchair = new ArmChair('http://localhost:5984/guestbook'); | |
$entry = array('entry' => 'Great guestbook!', 'author' => 'Till'); | |
$docData = $armchair->addDocument($entry); | |
$document = $armchair->getDocument($docData['id']); | |
$armchair->deleteDocument($docData['id']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment