CouchSource is a CakePHP datasource allowing to build Models from a CouchDB database.
This is the one in use on the PathMotion website.
After having set the couchdb engine, follow this steps to make it work with CakePHP :
-
Put the couch_source.php file into the datasource directory, usually
app/models/datasource
. -
Edit the database.php configuration file to add the following :
class DATABASE_CONFIG { // [...] var $couch = array( 'datasource' => 'couch', 'host' => '127.0.0.1', 'port' => 5984, 'user' => 'my_couchdb_user', 'password' => 'my_couchdb_password', 'auth_method' => 'cookie' // (or 'basic') ); }
-
create a model that you want to use CouchDB
class MyModel extends Model { public $name = 'MyModel'; public $useDbConfig = 'couch'; public $useTable = 'couchdb_database_name'; public $primaryKey = 'id'; // since CouchDB is shema-less, the fields here are only required // for CakePHP to validate and save them into the database public $_schema = array( 'id' => array( 'type' => 'string', 'key' => 'primary', 'length' => 32 ), 'anyfield' => array( 'type' => 'json', 'null' => true ), 'anotherfield' => array( 'type' => 'json', 'null' => true ) ); }
class MyModel extends Model {
function create_record() {
$this->save(array('MyModel' => array(
'anyfield' => 'anyvalue',
'anotherfield' => array(
'title' => 'awesome title'
'content' => 'less awesome content'
)
)));
}
}
class MyModel extends Model {
function update_record($id) {
$this->save(array('MyModel' => array(
'id' => $id,
'anyfield' => 'anyvalue',
'anotherfield' => array(
'title' => 'awesome title'
'content' => 'less awesome content'
)
)));
}
}
class MyModel extends Model {
function delete_record($id) {
$this->delete($id);
}
}
class MyModel extends Model {
function read_record($id) {
$this->findById($id);
}
}
The find params to use here are :
-
design : the CouchDB design where the view resides
-
view : the name of the view you want to request
-
params : an array of query options
class MyModel extends Model { function read_view($start, $end) { $this->find('all', array( 'design' => 'mycouchdbdesign', 'view' => 'mycouchdbview', 'params' => array('start_key' => $start, 'end_key' => $end, 'group' => null) )); } }