Search code examples
phpangularjscouchdbcloudant

Making simple operations in Cloudant using PHP


I have a simple SPA built with AngularJS. I'm attempting now to do 2 simple operations in a CouchDB hosted in Cloudant using a PHP file: save a document, and get all documents.

All premade examples of CRUD operations using PHP are extremely complex, using multiple dependencies and I didn't get far with them, as PHP is not really my thing.

The last one I tried is this one, it gives me a Cannot redeclare class Cloudant in /.../comanda/incoming/test/Cloudant.php on line 10 error and I didn't manage to fix it.

What I see in the code though, is how they make the server log in, and some get/put.

It looks like this:

class Cloudant {  

function __construct($server,$db,$username,$password){
  $username = 'user';
  $password = 'pass';
  $server = 'cloudant.com';
  $db = 'dbname';
  $this->server = "https://".$username.":".$password.'@'.$username.$server;
  $this->db = $db;
  $this->header_short = "Content-Type: application/json";
  $this->header = $this->header_short."\r\nContent-Length: ";
}



//curl -X PUT {USERNAME}:{PASSWORD}@{USERNAME}.cloudant.com/{DB}{/ID} -d ....
function upsert_doc( $id, $data ){ // to update - include _rev in document body
 return $this->call($id, array(
    'method' => 'POST', 
    'header' => $this->header . strlen($data) . "\r\n",
    'content' => $data));
}

//curl -X GET {USERNAME}:{PASSWORD}@{USERNAME}.cloudant.com/{DB}/{ID} 
function get( $id ){
 return $this->call($id, array(
    'method' => 'GET', 
    'header' => $this->header_short
 ));
} 

Any tips on how to simplify this? I'm looking into having one PHP file to make the authentication + saving JSON array, and another to authenticate + getting all documents.


Solution

  • The error is literally that you can't redeclare the class "Cloudant" because there's another one in your project somewhere - renaming this class should help with that.

    For talking to Cloudant from PHP, it's an HTTP interface so while there are libraries, you don't necessarily need one for some simple queries as you mentioned. I usually use Guzzle but you could use the curl extension or the built-in stream handlers. Some examples of PHP code that uses Guzzle to talk to Cloudant are here in a sample app I built, this might help give you some pointers: https://github.com/ibm-cds-labs/guestbook/blob/master/src/web/classes/Guestbook/CommentService.php