/**
  * @param string $databaseName
  * @return \MongoDB
  */
 private static function connectMongo($databaseName)
 {
     if (static::$_mongo == null) {
         static::$_mongo = new \Mongo();
     }
     return static::$_mongo->selectDB($databaseName);
 }
 /**
  * Initialize the mongodb collection
  *
  * @throws \RuntimeException
  */
 public function initialize()
 {
     if (null !== $this->collection) {
         return;
     }
     if (empty($this->dbOptions['database'])) {
         throw new \RuntimeException('The option "database" must be set');
     }
     if (empty($this->dbOptions['collection'])) {
         throw new \RuntimeException('The option "collection" must be set');
     }
     $this->collection = $this->mongo->selectDB($this->dbOptions['database'])->selectCollection($this->dbOptions['collection']);
 }
Beispiel #3
0
 /**
  * @return void
  */
 public function __construct($options)
 {
     if (!extension_loaded('mongo') && !extension_loaded('mongodb')) {
         \Zend_Cache::throwException('The MongoDB extension must be loaded for using this backend !');
     }
     parent::__construct($options);
     // Merge the options passed in; overridding any default options
     $this->_options = array_merge($this->_options, $options);
     $this->_conn = new \MongoClient('mongodb://' . $this->_options['host'] . ':' . $this->_options['port'], $this->_options['optional']);
     $this->_db = $this->_conn->selectDB($this->_options['dbname']);
     $this->_collection = $this->_db->selectCollection($this->_options['collection']);
     $this->_collection->ensureIndex(['t' => 1], ['background' => true]);
     $this->_collection->ensureIndex(['expire' => 1], ['background' => true]);
 }
Beispiel #4
0
 function __construct($db = null, $host = null)
 {
     $mongo = new Mongo($host);
     $database = $mongo->selectDB($db);
     $this->mongo = $mongo;
     $this->database = $database;
 }
Beispiel #5
0
 /**
  * $dsn has to contain db_name after the host. E.g. "mongodb://localhost:27017/mongo_test_db"
  *
  * @static
  * @param $dsn
  * @param $user
  * @param $password
  * @return \Mongo
  * @throws \Exception
  */
 public function __construct($dsn, $user, $password)
 {
     /* defining DB name */
     $this->dbName = substr($dsn, strrpos($dsn, '/') + 1);
     if (strlen($this->dbName) == 0) {
         throw new \Exception('Please specify valid $dsn with DB name after the host:port');
     }
     /* defining host */
     if (false !== strpos($dsn, 'mongodb://')) {
         $this->host = str_replace('mongodb://', '', $dsn);
     } else {
         $this->host = $dsn;
     }
     $this->host = rtrim(str_replace($this->dbName, '', $this->host), '/');
     $options = array('connect' => TRUE);
     if ($user && $password) {
         $options += array('username' => $user, 'password' => $password);
     }
     try {
         $m = new \Mongo($dsn, $options);
         $this->dbh = $m->selectDB($this->dbName);
     } catch (\MongoConnectionException $e) {
         throw new \Exception(sprintf('Failed to open Mongo connection: %s', $e->getMessage()));
     }
     $this->dsn = $dsn;
     $this->user = $user;
     $this->password = $password;
 }
Beispiel #6
0
 /**
  * Return a "MongoCollection" instance
  *
  * @return \MongoCollection
  */
 private function getCollection()
 {
     if (null === $this->collection) {
         $this->collection = $this->mongo->selectDB($this->options['database'])->selectCollection($this->options['collection']);
     }
     return $this->collection;
 }
Beispiel #7
0
 protected function conn()
 {
     if (!isset(self::$_db_handle[$this->db_config_name])) {
         if (false == ($iconfig = C($this->db_config_name, 'db'))) {
             show_error('数据库配制文件db.config.php中 ' . $this->db_config_name . '  未设置。');
         }
         $DSN = 'mongodb://';
         // exp: mongodb://192.168.1.222
         if ($iconfig['user']) {
             $DSN .= $iconfig['user'];
         }
         if ($iconfig['password']) {
             $DSN .= ':' . $iconfig['password'];
         }
         if ($DSN != 'mongodb://') {
             $DSN .= '@';
         }
         if ($iconfig['host']) {
             $DSN .= $iconfig['host'];
         }
         if (!empty($iconfig['port'])) {
             $DSN .= ':' . $iconfig['port'];
         }
         $mongoDB = new Mongo($DSN);
         self::$_db_handle[$this->db_config_name] = $this->db = $mongoDB->selectDB($iconfig['dbname']);
     } else {
         $this->db = self::$_db_handle[$this->db_config_name];
     }
     return $this->db;
 }
 /**
  * 构造查询
  *
  * @param Mongo $mongo MongoDB连接
  * @param string $db 数据库
  * @param string $collection 集合
  */
 function __construct(Mongo $mongo, $db, $collection)
 {
     $this->_dbName = $db;
     $this->_collectionName = $collection;
     $this->_db = $mongo->selectDB($this->_dbName);
     $this->_collection = $mongo->selectCollection($this->_dbName, $this->_collectionName);
 }
Beispiel #9
0
 function __construct()
 {
     $this->conf = new Conf();
     $m = new Mongo();
     $db = $m->selectDB($this->conf->db());
     $this->selfColl = $db->zone;
 }
Beispiel #10
0
 /**
  * Creates a mongo connection and connects.
  *
  * @throws MongoConnectionException, Exception
  * @return MongoDB database object
  */
 private function createInstance()
 {
     //Pull these from a config file
     jimport('sml.smlconfig');
     $conf = new SMLConfig();
     $serverList = $conf->mongo_hosts;
     $database = $conf->mongo_db;
     $persistent = $conf->mongo_persistent;
     $paired = $conf->mongo_paired;
     //End config entries
     if (count($serverList) > 2) {
         throw new Exception("Connection can be established to 2 or fewer instances only.");
     }
     if (count($serverList) == 2) {
         $paired = true;
         $servers = implode(',', $serverList);
     } else {
         $servers = $serverList[0];
     }
     try {
         $m = new Mongo($servers, true, $persistent, $paired);
         $db = $m->selectDB($database);
     } catch (Exception $e) {
         //we should swallow this, and likely put a site down message up..
         die('<pre>' . $e->getTraceAsString());
     }
     return $db;
 }
 public static function add_point($lat, $lon, $point_name)
 {
     $m = new Mongo();
     $db = $m->selectDB("your_db");
     $collection = $db->your_collection;
     $collection->insert(array("point_name" => $point_name, "loc" => array("lon" => $lon, "lat" => $lat)));
 }
Beispiel #12
0
 public function __construct()
 {
     $mongo = new Mongo();
     $mongoDb = $mongo->selectDB('ContactsManager');
     $this->contactsManagerCollection = new MongoCollection($mongoDb, 'Contact');
     $this->contactsManagerCollection->ensureIndex(array('email' => 1), array('unique' => true, 'dropDups' => true));
 }
 private function __construct()
 {
     $con = new Mongo("mongodb://" . MONGO_HOST . ":27017");
     $db = $con->selectDB(MONGO_DATABASE);
     // Connect to Database
     $this->mGrid = $db->getGridFS();
 }
Beispiel #14
0
 function __construct()
 {
     $this->conf = new Conf();
     $m = new Mongo();
     $db = $m->selectDB($this->conf->db());
     $this->placeColl = $db->place;
     $this->yakCatColl = $db->yakcat;
     $this->filesourceColl = $db->filesource;
     $this->title = '';
     $this->content = '';
     $this->thumb = '';
     $this->origin = '';
     $this->filesourceId = '';
     $this->filesourceTitle = '';
     $this->access = 1;
     $this->licence = '';
     $this->outGoingLink = '';
     $this->yakTag = array();
     $this->yakCat = array();
     $this->humanCat = array();
     $this->freeTag = array();
     $this->creationDate = time();
     $this->lastModifDate = time();
     $this->location = new Location();
     $this->address = new Address();
     $this->formatted_address = "";
     $this->contact = new Contact();
     $this->status = 0;
     $this->user = 0;
     $this->zone = 0;
 }
Beispiel #15
0
 private static function _UpdateReport($url, $reportName)
 {
     $_host = parse_url($url, PHP_URL_HOST);
     $_today = new MongoDate(strtotime('today'));
     $connected = false;
     while (!$connected) {
         try {
             $_mdb = new Mongo();
             $connected = true;
         } catch (MongoConnectionException $e) {
             //echo "\nMongoConnectionException: ".$e->getMessage();
             sleep(1);
         }
     }
     $_reports = $_mdb->selectDB("googleproxy")->reports;
     $_rowFilter = array('host' => $_host, 'date' => $_today);
     $success = false;
     while (!$success) {
         try {
             if (!$_reports->findOne($_rowFilter)) {
                 $_reports->insert(array_merge($_rowFilter, array(ReportType::CacheHitCount => array('count' => 0), ReportType::RequestCount => array('count' => 0))));
             }
             $success = true;
         } catch (MongoCursorException $e) {
             //echo "\nMongoCursorException: ".$e->getMessage();
             sleep(1);
         }
     }
     $_reports->ensureIndex(array('report' => 1, 'date' => 1), array('background' => true));
     $_update = array('$inc' => array($reportName . '.count' => 1));
     $_options['multiple'] = false;
     $_reports->update($_rowFilter, $_update, $_options);
 }
function insert_from_cursor()
{
    $m = new Mongo("localhost");
    $m->connect();
    $db = $m->selectDB("test-database");
    $collection = $db->successfulTweets;
    $successfulTweets = $collection->find();
    // echo "<pre>";
    foreach ($successfulTweets as $tweet) {
        // var_dump($tweet);
        $text = $tweet["text"];
        $author = $tweet["user_name"];
        $tweet_url = "https://twitter.com/statuses/" . $tweet["tweet_id"];
        $handle_url = "https://twitter.com/" . $tweet["user_name"];
        if ($tweet["tweet_id"] == Null) {
            $title = "<span>--manual_post<span>: " . $text;
            $content = "This post was manually submitted";
            $author = "--manual_post";
        } else {
            $title = "<span>" . $author . "</span>: " . $text . "<p> - [<a href=\"" . $tweet_url . "\" class=\"header-tweet-link\">link</a> | <a href=\"" . $handle_url . "\" class=\"header-handle-link\">@" . $author . "</a>]</p>";
            $content = "<a href=\"" . $tweet_url . "\">Check out the original tweet here: https://twitter.com/statuses/" . $tweet["tweet_id"];
            $author = $tweet["user_name"];
        }
        if ($tweet["tweeted_yet"] == True) {
            // echo "Already posted";
        } else {
            // echo "Not yet posted";
            $myPost = array('post_title' => $title, 'post_content' => $content, 'post_status' => 'publish', 'post_author' => $author);
            // var_dump($myPost);
            $collection->update(array('_id' => $tweet['_id']), array('$set' => array('tweeted_yet' => True)));
            $newVar = wp_insert_post($myPost);
        }
    }
    // echo "</pre>";
}
Beispiel #17
0
 /**
  * 构造函数,创建Mongo操作对象,并选择库,选择集合
  * @param $collection 集合名称
  */
 public function __construct($collection = 'guess_you_like_document')
 {
     $conn = new Mongo('mongodb://othermongodb:30000');
     $db = $conn->selectDB('cms');
     $this->myCollection = $db->selectCollection($collection);
     return $this->myCollection;
 }
 public function connect()
 {
     // Connect to the database and return the collection
     $mongo = new Mongo('mongodb://localhost');
     $db = $mongo->selectDB('test');
     return $db->selectCollection('locations');
 }
 public function __construct()
 {
     $debugOutput = false;
     $mongoDir = "/usr";
     if (!file_exists($mongoDir . '/bin/mongod')) {
         throw new PHPUnit_Framework_SkippedTestError('mongo daemon not found');
     }
     static $m;
     if (!isset($m)) {
         $port = Kwf_Util_Tcp::getFreePort(rand(27020, 30000));
         $cmd = "php " . KWF_PATH . "/bootstrap.php test forward --controller=kwf_model_mongo_run-temp-mongo --port={$port}";
         if ($debugOutput) {
             echo $cmd . "\n";
             $descriptorspec = array(1 => STDOUT, 2 => STDOUT);
         } else {
             $cmd .= " 2>&1 >/dev/null";
             $descriptorspec = array(1 => array('pipe', 'w'), 2 => STDOUT);
         }
         self::$_proc = new Kwf_Util_Proc($cmd, $descriptorspec);
         sleep(3);
         $m = new Mongo("mongodb://localhost:{$port}");
         register_shutdown_function(array('Kwf_Model_Mongo_TestModel', 'shutDown'));
     }
     $db = $m->selectDB("modeltest");
     $db->selectCollection($this->_collection)->drop();
     $config = array('db' => $db);
     parent::__construct($config);
 }
Beispiel #20
0
 static function db()
 {
     if (is_null(self::$_db)) {
         $conn = new Mongo();
         self::$_db = $conn->selectDB(self::get_config('db_name'));
     }
     return self::$_db;
 }
Beispiel #21
0
 /**
  * Constructs a new memcache cache driver and sets its configuration.
  * 
  * @param array $config The Memcache configuration.
  * 
  * @return Mongo
  */
 public function __construct(array $config = [])
 {
     $this->config = array_merge($this->config, $config);
     $mongo = new \Mongo($this->config['dsn'], $this->config['options']);
     $mongodb = $mongo->selectDB($this->config['db']);
     $this->collection = $mongodb->selectCollection($this->config['collection']);
     $this->collection->ensureIndex(['_id' => 1, 'expires' => 1], ['background' => true]);
 }
Beispiel #22
0
 /**
  * Simple connect method to get the database queries up and running.
  *
  * @return  void
  */
 public function connect()
 {
     if (!is_object($this->link)) {
         $mc = new Mongo($this->dsn);
         // Select the DB
         $this->link = $mc->selectDB($this->name);
     }
 }
Beispiel #23
0
 /**
  * @return \MongoCollection
  */
 public function getCollection()
 {
     if (!$this->collection) {
         $mongo = new \Mongo(sprintf('mongodb://%s', implode(',', $this->settings['servers'])));
         $this->collection = $mongo->selectDB($this->settings['database'])->selectCollection($this->settings['collection']);
     }
     return $this->collection;
 }
 public function __construct()
 {
     $m = new Mongo();
     $db = $m->selectDB("tribunal");
     $this->Incidents = $db->incidents;
     $this->Cases = $db->cases;
     $this->ReportedChampions = $db->reported_champions;
     $this->ReportReasons = $db->report_reasons;
 }
Beispiel #25
0
 /**
  * Get collection
  *
  * @return \MongoCollection
  */
 protected function _getCollection()
 {
     if (null === $this->_collection) {
         $connection = new \Mongo($this->_options['connection_string'], $this->_options['mongo_options']);
         $database = $connection->selectDB($this->_options['db']);
         $this->_collection = $database->selectCollection($this->_options['collection']);
     }
     return $this->_collection;
 }
 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before a test is executed.
  *
  * @access protected
  */
 protected function setUp()
 {
     $m = new Mongo();
     $db = $m->selectDB('phpunit');
     $grid = $db->getGridFS();
     $grid->drop();
     $grid->storeFile('tests/somefile');
     $this->object = $grid->find();
     $this->object->start = memory_get_usage(true);
 }
 /**
  * Will attempt to use the name for the database, if can't find it will throw
  * an error
  * 
  * @param String $name of the database 
  */
 public function setDatabase($name = "")
 {
     ValidatorsUtil::isNullOrEmpty($this->_mongo, "Mongo Object isn't valid, have you 'open' a  new connection to the database yet?");
     if (ValidatorsUtil::isNullOrEmpty($name, "Mongo Database must have a name", true)) {
         if (!ValidatorsUtil::isNullOrEmpty($this->name, "Mongo Database must have a name")) {
             $name = $this->name;
         }
     }
     $this->_mongoDatabase = $this->_mongo->selectDB($name);
 }
Beispiel #28
0
 /**
  * Initialises the store instance for use.
  *
  * This function is reponsible for making the connection.
  *
  * @param cache_definition $definition
  * @throws coding_exception
  */
 public function initialise(cache_definition $definition)
 {
     if ($this->is_initialised()) {
         throw new coding_exception('This mongodb instance has already been initialised.');
     }
     $this->definitionhash = $definition->generate_definition_hash();
     $this->connection = new Mongo($this->server, $this->options);
     $this->database = $this->connection->selectDB($this->databasename);
     $this->collection = $this->database->selectCollection($this->definitionhash);
     $this->collection->ensureIndex(array('key' => 1), array('safe' => $this->usesafe, 'name' => 'idx_key'));
 }
    public function testGetter() {
      if (preg_match("/5\.1\../", phpversion())) {
        $this->markTestSkipped("No implicit __toString in 5.1");
        return;
      }

      $db = $this->object->selectDB('db');
      $this->assertEquals('db', $db->__toString());
      $db = $this->object->selectDB($db);
      $this->assertEquals('db', $db->__toString());
    }
Beispiel #30
0
 /**
  * Open the connection
  * @return MongoDB
  */
 public function open()
 {
     $meta = $this->getMeta();
     $connection = isset($meta['db']['host']) && '' != trim($meta['db']['host']) ? $meta['db']['host'] : 'localhost';
     $connection .= isset($meta['db']['port']) && '' != trim($meta['db']['port']) ? ':' . intval($meta['db']['port']) : '';
     if (isset($meta['db']['user']) && '' != trim($meta['db']['user'])) {
         $credentials = $meta['db']['user'];
         if (isset($meta['db']['password']) && '' != trim($meta['db']['password'])) {
             $credentials .= ':' . $meta['db']['password'];
         }
         $connection = $credentials . '@' . $connection;
     }
     try {
         $this->_connection = new Mongo('mongodb://' . $connection);
         $this->_database = $this->_connection->selectDB($meta['db']['database']);
     } catch (Exception $e) {
         throw new One_Exception('Could not connect: ' . $e->getMessage());
     }
     return $this->_database;
 }