DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Languages
  4. Using CouchDb as a filesystem with PHP

Using CouchDb as a filesystem with PHP

Gonzalo Ayuso user avatar by
Gonzalo Ayuso
·
Dec. 19, 11 · Interview
Like (0)
Save
Tweet
Share
6.69K Views

Join the DZone community and get the full member experience.

Join For Free

one of the problems i need to solve in my clustered php applications is where to store files. when i say files i’m not speaking about source code. i’m speaking about additional data files, such as download-able pdfs, logs, etc. those files must be on every node of the cluster. one possible approach to the solution is to use a distributed filesystem, rsync or maybe use a file-server mounted on every node. another solution may be the usage of couchdb. couchdb has two great features to meet or requirements with this problem. it allows us to store files as attachments and it also allows to perform a great and very easy multi-master replica system.

the usage of couchdb is pretty straightforward. it implements a restfull interface to perform every operations. so the only thing we need is a rest client. zend framework has a great one . we dont’t really need a library. we can easily perform rest requests with the php’s curl’s extension . i’ve created two libraries for working with couchdb one is a low-level http client (with curl) and another is higher level one (it uses the http client) for couchdb operations. you can read two post about those libraries here and here .

now i want to extend the features of my library. i want to use couchdb as file storage in php. instead of using file functions (fopen, fwrite, fread, …) i want to use another ones and store/read files in couchdb. for doing this i’ve refactored those two libraries into another one called nov . i also have embraced namespaces so i will use them in the library. this means it’s only available with php 5.3.

here you are a summary of the library. that’s not a complete uml graph. it’s only a diagram with the main features only with educational purpose.

summary

the best to show the library is with an example:

first i’m going to start with the basic usage of nov\couchdb library:

// starting up the loader
require_once("nov/loader.php");
nov\loader::init();

use nov\couchdb;
$cdb = new couchdb('localhost', 5984);
$cdb->db('users');
$nombre = $cdb->db('ris_users')->select('gonzalo')->asobject()->name;
$apellido = $cdb->db('ris_users')->select('gonzalo')->asobject()->surname;
echo "hello {$nombre} {$apellido}.
";

to allow me the use of different couchdb databases and to put the database configuration in one file. i use the following configuration class:

class novconf
{
    const cdb1 = 'cdb1';
    const pg1  = 'pg1';

    public static $_dbs = array(
    	self::pg1  => array(
            'driver'   => 'pgsql',
            'dsn'      => 'pgsql:dbname=pg1;host=localhost',
            'username' => null
            'password' => null,
        ),
        self::cdb1  => array(
            'driver'   => 'couchdb',
            'host'     => 'localhost',
            'port'     => 5984,
            'protocol' => 'http',
            'username' => null,
            'password' => null,
        ),
    );
}

as you can see i use the same configuration file for my pdo drivers and couchdb.

now i can use:

require_once("nov/loader.php");
nov\loader::init();

use nov\couchdb;
$cdb = couchdb::factory(novconf::cdb1)->db('users');

try {
    $cdb->insert('xxx', array('name' => 'xxx'));
} catch (couchdb\exception\dupvalonindex $e) {
    echo "already created\n";
}

$data = $cdb->select('xxx')->asobject();
$cdb->update('xxx', array('name' => 'xxx1'));
$cdb->delete('xxx')->asobject();
require_once("nov/loader.php");
nov\loader::init();

use nov\couchdb;
$cdb = couchdb::factory(novconf::cdb1)->db('users');

try {
    $cdb->insert('xxx', array('name' => 'xxx'));
} catch (couchdb\exception\dupvalonindex $e) {
    echo "already created\n";
}

$data = $cdb->select('xxx')->asobject();
$cdb->update('xxx', array('name' => 'xxx1'));
$cdb->delete('xxx')->asobject();

and now finally the file storage part:

for storing the files i’ve taken one design decision. every files will be stored into separate couchdb document. that’s means one file, one document. there’s another possible approach. one couchdb document can be one folder and store every files as attachments of this folder in the same document. but i prefer the idea of not to track folders. only files. so each couchdb document will have only one attachment.

that’s an example of one document in couchdb

{
   "_id": "/home/gonzalo/aasa.txt",
   "_rev": "2-48b501a81c38fd84a3e0351917e64135",
   "path": "/home/gonzalo",
   "_attachments": {
       "aasa.txt": {
           "stub": true,
           "content_type": "application/octet-stream",
           "length": 12,
           "revpos": 2
       }
   }
}

there’s another usage script. here we can see all the features together. we create files, update and delete them. internally nov\couchdb\fs uses a predefined couchdb database called fs.

use nov\couchdb\fs;
use nov\couchdb\fs\exception;
require_once ("nov/loader.php");
nov\loader::init();

echo "<pre>";
// create an instance from a factory method
$fs = fs::factory(novconf::cdb1);
// now we're going to delete a file. if it doesn't exists will throw a filenotfound exception
try {
    $fs->delete("/home/gonzalo/aaa.txt");
} catch (exception\filenotfound  $e) {
    echo $e->getmessage() . "\n";
}
// now we are going to create a file.
// the second parameter 'true' means if the file doesn't exist will be created. similar than 'r+'
try {
    $fs->open("/home/gonzalo/aaa.txt", true)
	->write("asasasasasas", "application/octet-stream");
} catch (exception\filenotfound $e) {
    echo $e->getmessage() . "\n";
} catch (exception\writeerror $e) {
    echo $e->getmessage() . "\n";
} catch (exception $e) {
    echo $e->getmessage() . "\n";
}
// we open the file
$res = $fs->open("/home/gonzalo/aaa.txt");

// we can get the length and the content type
echo $res->getlenght() . "\n";
echo $res->getcontenttype(). "\n";
// we move it to another location
$to = "/another/location";
$res->move($to);

$res = $fs->open($to);
// we flush the file to the browser
echo $res->raw();

// finally we delete it
$res->delete();
echo "</pre>";

i’ve also created an extra class to allow to dump files from filesystem to couchdb and vice-versa.

require_once ("nov/loader.php");
nov\loader::init();
echo "<pre>";
// from filesystem to couchdb
\nov\couchdb\fs\utils::fs2cdb("/path/from/", novconf::cdb1);
// from couchdb to filesystem
\nov\couchdb\fs\utils::cdb2fs(novconf::cdb1, "/path/to/");
echo "</pre>";

and that’s all. you can download the source code with the examples here . the examples are under document_root/tests/couchdb/ folder. remember you will need php5.3.

source: http://gonzalo123.wordpress.com/2010/08/30/using-couchdb-as-filesystem-with-php/

PHP Library

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 10 Most Popular Frameworks for Building RESTful APIs
  • What Is Advertised Kafka Address?
  • Getting a Private SSL Certificate Free of Cost
  • How To Best Use Java Records as DTOs in Spring Boot 3

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: