Skip to content

Instantly share code, notes, and snippets.

@n1k0
Created February 22, 2010 08:42
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 n1k0/310931 to your computer and use it in GitHub Desktop.
Save n1k0/310931 to your computer and use it in GitHub Desktop.
sfDatabase compatible MongoDB database backend driver
<?php
/**
* sfDatabase compatible MongoDB database backend driver
*
* @package database
* @author Nicolas Perriault
*/
class sfMongoDatabase extends sfDatabase
{
/**
* Connects to the database.
*
* @throws sfDatabaseException If a connection could not be created
*/
public function connect()
{
$database = $this->getParameter('database');
$host = $this->getParameter('host', 'localhost');
$password = $this->getParameter('password');
$username = $this->getParameter('username');
$port = $this->getParameter('port',27017);
$persistent = $this->getParameter('persistent', true);
$paired = $this->getParameter('paired', false);
try
{
$this->connection = $this->resource = new Mongo(sprintf('%s:%s', $host, $port), true, $persistent, $paired);
}
catch (Exception $e)
{
throw new sfDatabaseException(sprintf('Cannot connect to mongodb server on "%s@%s:%d (password: %s)"', $username, $host, $port, $password ? 'yes' : 'no'));
}
}
/**
* Selects the database to be used in this connection
*
* @param string $database Name of database to be connected
*
* @return Boolean
*/
protected function selectDatabase($database)
{
return ($database != null && !$this->connection->selectDB($database));
}
/**
* Loads connection parameters from an existing array.
*
* @return array An associative array of connection parameters
*/
protected function &loadParameters(&$array)
{
$available = array('database', 'host', 'password', 'username', 'port', 'persistent', 'paired');
$parameters = array();
foreach ($available as $parameter)
{
$$parameter = $this->getParameter($parameter);
$parameters[$parameter] = $$parameter != null ? $array[$$parameter] : null;
}
return $parameters;
}
/**
* Execute the shutdown procedure
*
*/
public function shutdown()
{
if ($this->connection != null)
{
$this->connection = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment