本文整理汇总了PHP中MongoClient类的典型用法代码示例。如果您正苦于以下问题:PHP MongoClient类的具体用法?PHP MongoClient怎么用?PHP MongoClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MongoClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: sendMongo
function sendMongo($steamId, $type)
{
//function mongoConnect($steamId,$type,$collection){
switch ($type) {
case 1:
//gets the player Summaries
$fetch_pInfo = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?\t\tkey=238E8D6B70BF7499EE36312EF39F91AA&steamids={$steamId}";
break;
case 2:
//gets the players Game Library
$fetch_pInfo = "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=238E8D6B70BF7499EE36312EF39F91AA&steamid={$steamId}&format=json";
break;
/*
case 3://gets the players achievements
//steam api for players achievements.
break;
case 4://may have to get other stats,
//will use this maybe for players over all steam rank.
break;
*/
}
//end switch data
$jsonO = file_get_contents($fetch_pInfo);
var_dump($jsonO);
$connection = new MongoClient("mongodb://alex:password@ds041643.mongolab.com:41643/steamdata");
$mongodb = $connection->selectDB('steamdata');
$collection = new MongoCollection($mongodb, 'gameLibrary');
//var_dump($connection);
//var_dump($collection);
$send = array();
$send["_id"] = $steamId;
$send["info"] = $jsonO;
$collection->insert($send);
}
示例2: like
function like($user, $id, $channel)
{
try {
$conn = new MongoClient();
$db = $conn->site;
$collection = $db->users;
$testquery = array('user_name' => $user);
$cursor = $collection->find($testquery);
if ($cursor->count() == 0) {
$info = array('user_name' => $user, '_id' => $id, 'likes' => 1);
$collection->insert($info);
$collection->update(array('user_name' => $user), array('$addToSet' => array('liked_channels' => $channel)));
echo "liked";
} else {
$collection->update(array('user_name' => $user), array('$inc' => array('likes' => 1)));
$collection->update(array('user_name' => $user), array('$addToSet' => array('liked_channels' => $channel)));
//$collection->update(array('user_name' => $user), array('$addToSet' => array('liked_channels' => $channel), '$setOnInsert' => array('$inc' => array('likes' => 1))), array('upsert' => true));
echo "liked";
}
$conn->close();
} catch (MongoConnectionException $e) {
echo 'Error connecting to MongoDB server';
} catch (MongoException $e) {
echo 'Error somewhere else with mongo';
}
//die('Error: ' . $e->getMessage()); }
exit;
}
示例3: execute
public function execute()
{
parent::execute();
// Make sure all required parameters are used
$required_parameters = array('id');
foreach ($required_parameters as $parameter) {
if (!array_key_exists($parameter, $_GET)) {
echo json_encode(array('error' => 'Missing parameter: \'' . $parameter . '\''));
exit;
}
}
// Initialize database
try {
$m = new \MongoClient('mongodb://' . MONGODB_USERNAME . ':' . MONGODB_PASSWORD . '@' . MONGODB_HOST . '/' . MONGODB_DATABASE);
$db = $m->selectDB(MONGODB_DATABASE);
} catch (MongoConnectionException $e) {
echo json_encode(array('error' => 'Database connection failed, please try again later'));
exit;
}
// Query database
$result = $db->interactions->findOne(array('_id' => new MongoId($_GET['id'])));
// Output JSON data
if (is_null($result)) {
echo json_encode(array('error' => 'Message doesn\'t exist'));
} else {
echo json_encode($result);
}
}
示例4: __construct
function __construct($databaseName)
{
$server = "mongodb://localhost:27017/";
$m = new MongoClient($server);
$this->db = $m->selectDB($databaseName);
$this->postsCollection = $this->db->selectCollection('testposts');
}
示例5: setupmongo
function setupmongo()
{
//sets up a mongo connection
$mongo = new MongoClient("mongodb://technicolor:testbed@localhost/backendtest");
$collection = $mongo->selectDB('backendtest')->selectCollection('user');
return $collection;
}
示例6: setDatabase
function setDatabase($di, $host, $db)
{
$di->set('api_db', function () use($host, $db) {
$mongo = new MongoClient($host);
return $mongo->selectDB($db);
}, true);
}
示例7: register
/**
* {@inheritdoc}
* @see http://docs.phalconphp.com/pl/latest/reference/odm.html
*/
public function register(DiInterface $di)
{
$di->set(self::SERVICE_NAME, function () use($di) {
$mongoConfig = $di->get('config')->mongo->toArray();
if (isset($mongoConfig['dsn'])) {
$hostname = $mongoConfig['dsn'];
unset($mongoConfig['dsn']);
} else {
//obtains hostname
if (isset($mongoConfig['host'])) {
$hostname = 'mongodb://' . $mongoConfig['host'];
} else {
$hostname = 'mongodb://localhost';
}
if (isset($mongoConfig['port'])) {
$hostname .= ':' . $mongoConfig['port'];
}
//removes options that are not allowed in MongoClient constructor
unset($mongoConfig['host']);
unset($mongoConfig['port']);
}
$dbName = $mongoConfig['dbname'];
unset($mongoConfig['dbname']);
$mongo = new \MongoClient($hostname, $mongoConfig);
return $mongo->selectDb($dbName);
}, true);
}
示例8: __construct
/**
* $dsn has to contain db_name after the host. E.g. "mongodb://localhost:27017/mongo_test_db"
*
* @static
*
* @param $dsn
* @param $user
* @param $password
*
* @throws ModuleConfigException
* @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 ModuleConfigException($this, '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 = ['connect' => true];
if ($user && $password) {
$options += ['username' => $user, 'password' => $password];
}
try {
$m = new \MongoClient($dsn, $options);
$this->dbh = $m->selectDB($this->dbName);
} catch (\MongoConnectionException $e) {
throw new ModuleException($this, sprintf('Failed to open Mongo connection: %s', $e->getMessage()));
}
$this->dsn = $dsn;
$this->user = $user;
$this->password = $password;
}
示例9: register
public function register(Application $app, array $config = [])
{
// apply default options
$defaultClientOptions = ['server' => 'mongodb://localhost:27017', 'options' => ['connect' => true], 'driver_options' => []];
if (isset($app['mongodb.mongo_client_options'])) {
$app['mongodb.mongo_client_options'] = array_merge($defaultClientOptions, $app['mongodb.mongo_client_options']);
} else {
$app['mongodb.mongo_client_options'] = $defaultClientOptions;
}
// apply config parameter
if (isset($config['mongodb.mongo_client_options'])) {
$app['mongodb.mongo_client_options'] = array_merge($app['mongodb.mongo_client_options'], $config['mongodb.mongo_client_options']);
}
if (isset($config['mongodb.db'])) {
$app['mongodb.db'] = $config['mongodb.db'];
}
// create service container
$app['mongodb.mongo_client'] = $app->share(function () use($app) {
$mongoClient = new \MongoClient($app['mongodb.mongo_client_options']['server'], $app['mongodb.mongo_client_options']['options'], $app['mongodb.mongo_client_options']['driver_options']);
if (isset($app['mongodb.db'])) {
$mongoClient->selectDB($app['mongodb.db']);
}
return $mongoClient;
});
}
示例10: connect
public function connect()
{
// Connect to the database and return the collection
$mongo = new MongoClient('mongodb://localhost');
$db = $mongo->selectDB('test');
return $db->selectCollection('locations');
}
示例11: get_connection
function get_connection()
{
$connecting_string = sprintf('mongodb://%s:%d/%s', HOST, POST, DB);
$connection = new MongoClient($connecting_string);
$connection->selectDB("test");
return $connection;
}
示例12: getConnection
function getConnection($cache = false)
{
static $first;
$conf = new \ActiveMongo2\Configuration(__DIR__ . "/tmp/mapper.php");
$conf->addModelPath(__DIR__ . '/docs')->development();
if (!empty($_SERVER["NAMESPACE"])) {
if (!$first) {
print "Using namespace {$_SERVER['NAMESPACE']}\n";
}
$conf->SetNamespace($_SERVER["NAMESPACE"]);
}
if (!$first) {
$mongo = new MongoClient();
$mongo->selectDB('activemongo2_tests')->drop();
$mongo->selectDB('activemongo2_tests_foobar')->drop();
$config = new ActiveMongo2\Configuration();
unlink($config->getLoader());
}
if (empty($_SERVER["NAMESPACE"])) {
$zconn = new \ActiveMongo2\Client(new MongoClient(), 'activemongo2_tests', __DIR__ . '/docs');
} else {
$zconn = new \ActiveMongo2\Connection($conf, new MongoClient(), 'activemongo2_tests');
}
$zconn->AddConnection('foobar', new MongoClient(), 'activemongo2_tests_foobar', 'zzzz');
if ($cache) {
$zconn->setCacheStorage(new \ActiveMongo2\Cache\Storage\Memory());
}
$first = true;
return $zconn;
}
示例13: connect
public function connect($servers, $options = null)
{
if (empty($servers)) {
$this->error('not enough information to connect to mongodb.');
}
if (empty($options)) {
$options = array('connect' => true);
}
// checking dependency
if (!class_exists('MongoClient')) {
$this->error('no mongo client class. remember to sudo pecl install mongo.');
}
try {
$connection = new MongoClient($servers, $options);
$ok = $connection->connect();
if (!$ok) {
$this->error('could not connect to mongo.');
}
self::$___connection = $connection;
} catch (Exception $e) {
$this->error('couldn\'t connect to the mongo:' . $e->getMessage());
}
$this->log('connected to ' . $servers . '.');
return self::$___connection;
}
示例14: goForIt
function goForIt()
{
$mongo = new MongoClient();
$emails = $mongo->selectDB('emails_tester')->selectCollection('emails');
$servers = ['tcp://gmail-smtp-in.l.google.com:25', 'tcp://alt1.gmail-smtp-in.l.google.com:25', 'tcp://alt2.gmail-smtp-in.l.google.com:25', 'tcp://alt3.gmail-smtp-in.l.google.com:25', 'tcp://alt4.gmail-smtp-in.l.google.com:25'];
/** @var Client[] $clients */
$clients = [];
$loop = React\EventLoop\Factory::create();
$logger = new \Zend\Log\Logger();
$writer = new \Zend\Log\Writer\Stream('php://output');
$logger->addWriter($writer);
$logger->info('Creating clients.');
$start = microtime(1);
$checked = 0;
for ($i = 0; $i < 100; $i++) {
$client = new Client($loop, function ($record) use(&$checked, $emails, $start, $logger) {
$record['state'] = 'valid';
$emails->save($record);
$checked++;
if ($checked % 1000 == 0) {
$logger->info("Checked: {$checked}. Speed: " . $checked / (microtime(1) - $start) . " emails/sec.");
}
}, function ($record, $reason) use(&$checked, $emails, $start, $logger) {
$record['state'] = 'invalid';
$emails->save($record);
if ($reason !== false) {
$logger->warn("Email <{$record['email']}> failed check: {$reason}");
}
$checked++;
if ($checked % 1000 == 0) {
$logger->info("Checked: {$checked}. Speed: " . $checked / (microtime(1) - $start) . " emails/sec.");
}
});
$clients[] = $client;
}
$logger->info('Done.');
$loop->addPeriodicTimer(0.001, function () use($clients, $emails, $servers, $logger) {
foreach ($clients as $c) {
if ($c->getState() === Client::STATE_DISCONNECTED) {
$logger->info(spl_object_hash($c) . ": connecting...");
$c->connect($servers[mt_rand(0, count($servers) - 1)]);
return;
}
if ($c->getState() === Client::STATE_BUSY) {
continue;
}
if ($c->getState() === Client::STATE_IDLE) {
$record = $emails->findOne(['state' => ['$exists' => false]]);
if (!isset($record['email'])) {
continue;
}
$record['state'] = 'in_progress';
$emails->save($record);
$c->checkEmail($record);
continue;
}
}
});
$loop->run();
}
示例15: getCollection
function getCollection()
{
global $_server_name2, $_server_port2;
$m = new MongoClient("{$_server_name2}:{$_server_port2}");
$db = $m->selectDB("mysqlTableComment");
return $db->fieldComment;
}