Skip to content

Instantly share code, notes, and snippets.

@squallstar
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save squallstar/1e2642fd041ac9227907 to your computer and use it in GitHub Desktop.
Save squallstar/1e2642fd041ac9227907 to your computer and use it in GitHub Desktop.
Mongo PHP Helper
<?php
$GLOBALS['__DB'] = false;
function collection($name = FALSE)
{
if (!$GLOBALS['__DB'])
{
$connection = new MongoClient("http://localhost:27017");
$dbname = "database_name";
$GLOBALS['__DB'] = $connection->$dbname;
}
return $key ? $GLOBALS['__DB']->$key : $GLOBALS['__DB'];
}
function next_id($sequence)
{
$ret = collection('counters')->findAndModify(
array('_id' => $sequence . '_id'),
array('$inc' => array('seq' => 1)),
null,
array('new' => true)
);
return $ret['seq'];
}
<?php
$users = new MongoCollection(collection(), 'users');
$users->ensureIndex(array('email' => 1), array('unique' => true));
$counters = new MongoCollection(collection() 'counters');
$counters->insert(array('_id' => 'user_id', 'seq' => 0));
collection('users')->insert([
'_id' => next_id('user')
'text' => 'Hello world'
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment