Last active
August 29, 2015 14:05
-
-
Save squallstar/1e2642fd041ac9227907 to your computer and use it in GitHub Desktop.
Mongo PHP Helper
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 | |
$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']; | |
} |
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 | |
$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