Posts Tagged ‘mongodb’

Symfony mongodb logger

January 9th, 2010

Thanks for the elegant design of symfony framework, we can easily create a new logger by extending sfLogger.

/**
 * opMongoLogger logs messages in a mongo database.
 *
 * @author     Jayson Xu(http://www.doupie.com) 
*/
class opMongoLogger extends sfLogger
{
  protected
    $timeFormat = '%b %d %H:%M:%S';
  /**
   * Initializes this logger.
   *
   * Available options:
   *
   * - database:      a database name to store the cache in
   * - host:         the host of database
   * - port:         the host of port
   * - collection:   the host of collection
   *
   * @param  sfEventDispatcher $dispatcher  A sfEventDispatcher instance
   * @param  array             $options     An array of options.
   *
   * @return Boolean      true, if initialization completes successfully, otherwise false.
   */
  public function initialize(sfEventDispatcher $dispatcher, $options = array())
  {

    if (!class_exists('Mongo'))
    {
      throw new sfInitializationException(sprintf('the mongodb extension is not installed or enable, cannot use opMongoLogger.'));
    }
    parent::initialize($dispatcher, $options);

    if (!$this->hasOption('database'))
    {
      throw new sfInitializationException(sprintf('You must provide a database name to store the cache in'));
    }
    $this->type = $this->getOption('type','m');
    $this->database = $this->getOption('database');
    $this->host = $this->getOption('host','127.0.0.1');
    $this->port = $this->getOption('port','27017');
    $this->collection = $this->getOption('collection','logs');
    try
    {
      $this->handler = new mongo($this->host.":".$this->port);
      $this->coll_db = $this->handler->selectDB($this->database)->selectCollection($this->collection);
    }
    catch (Exception $e)
    {
      throw new sfInitializationException(sprintf('Could not connect to mongo database : ', $e->getMessage()));
    }

    if (isset($options['time_format']))
    {
      $this->timeFormat = $options['time_format'];
    }
    return true;
  }

  /**
   * Logs a message.
   *
   * @param string $message   Message
   * @param string $priority  Message priority
   */
  protected function doLog($message, $priority)
  {
    $log = array(
      'type'      => $this->type,
      'message'   => $message,
      'time'      => strftime($this->timeFormat),
      'priority'  => $this->getPriority($priority),
      );
    if(sfContext::getInstance())
    {
      $log['module'] = sfContext::getInstance()->getRequest()->getParameter('module');
      $log['action'] = sfContext::getInstance()->getRequest()->getParameter('action');
    }
    $this->coll_db->insert($log);
  }

  /**
   * Returns the priority string to use in log messages.
   *
   * @param  string $priority The priority constant
   *
   * @return string The priority to use in log messages
   */
  protected function getPriority($priority)
  {
    return sfLogger::getPriorityName($priority);
  }

  /**
   * Executes the shutdown method.
   */
  public function shutdown()
  {
    $this->handler->close();
  }

  public function hasOption($option)
  {
    return array_key_exists($option, $this->options);
  }

    /**
   * Gets an option value.
   *
   * @param string $name    The option name
   * @param mixed  $default The default value
   *
   * @return mixed The option value
   */
  public function getOption($name, $default = null)
  {
    return isset($this->options[$name]) ? $this->options[$name] : $default;
  }
}

in opMongoLogger, if the logger is called from action, it will log the module and action too.

mongo php 入门

January 9th, 2010

创建数据库连接

$connection = new Mongo(); //连接到localhost:27017
$connection = new Mongo( "example.com" ); // 连接到远程主机 (默认端口)
$connection = new Mongo( "example.com:65432" ); // 连接到特定端口的远程主机

获得一个数据库

如果想要获得的数据库不存在,mongodb会自动创建一个,而不会给出错误提示

$db = $connection->dbname;

获得一个集合

集合(collection)相当于关系型数据库中的表

$db = $connection->baz
$collection = $db->foobar;
//或者
$collection = $connection->baz->foobar;

插入一个文档

文档(document)相当于关系型数据库中的一条记录,mongo可以使用一个关联数组做为一条记录

$doc = array( "name" => "MongoDB",
   "type" => "database",
   "count" => 1,
   "info" => (object)array( "x" => 203,
       "y" => 102),
   "versions" => array("0.9.7", "0.9.8", "0.9.9")
);
$m = new Mongo();
$collection = $m->foo->bar;
$collection->insert( $doc );

查找

$obj = $collection->findOne(); //查找一个文档
echo $collection->count();//统计集合中文档数量
//使用游标获得所有的文档
$cursor = $collection->find();
foreach ($cursor as $id => $value) {
    echo "$id: ";
    var_dump( $value );
}

//条件查询
$query = array( "i" => 71 );
$cursor = $collection->find( $query );
while( $cursor->hasNext() ) {
    var_dump( $cursor->getNext() );
}

//创建索引
$coll->ensureIndex( array( "i" => 1 ) );  // create index on "i"
$coll->ensureIndex( array( "i" => -1, "j" => 1 ) );  // index on "i" descending, "j" ascending