Mongo
Jump to navigation
Jump to search
Backup
Dir Structure
mongodump -d games -o games.bak/
PHP
Basic PHP Mongo OO Example
Used from http://techportal.inviqa.com/2010/11/30/using-mongodb-in-php-applications/
//index.php
<?php
require_once("gameClass.php");
$m = new Mongo("localhost");
$gamePeer = new GamePeer($m->selectDb("games"));
$id = new MongoId("511a6286d0eff4ff64000000");
foreach ($gamePeer->fetchById($id) as $game)
{
print_r($game);
}
?>
//gameClass.php
<?php
class Game
{
private $gameId;
private $gameTitle;
//gameId is a mongoId type
public function Game($opts = Array())
{
//existing game
if(isset($opts['gameId']))
{
$this->gameId = $opts['gameId'];
}
}
public function getGameId()
{
return $this->gameId;
}
public function setGameId($gameId)
{
$this->gameId = $gameId;
}
public function getGameTitle()
{
return $this->gameTitle;
}
public function setGameTitle($gameTitle)
{
$this->gameTitle = $gameTitle;
}
}
class GamePeer
{
const COLLECTION = 'games';
const ID_FIELD = 'title';
const DB_ID_FIELD = '_id';
private $db;
private $coll;
public function __construct(MongoDb $db)
{
$this->db = $db;
}
private function getCollection()
{
// if the collection is not already cached
if (empty($this->collection))
{
// selects the collection if it exists
$this->collection = $this->db->selectCollection(self::COLLECTION);
// or creates a new one if it doesn't
if (empty($this->collection))
{
$this->collection = $this->db->createCollection(self::COLLECTION);
}
}
return $this->collection;
}
public function fetchAll()
{
// perform a find with a blank query
return $this->getCollection()->find();
}
public function fetchById($id)
{
$crit = Array('_id' => $id);
$result = $this->getCollection()->findOne($crit);
if($result)
{
return $result;
}
}
}
?>