首页 > 作文

php实现的mongodb操作类实例

更新时间:2023-04-06 09:16:19 阅读: 评论:0

本文实例讲述了php实现的mongodb操作类。分享给大家供大家参考。具体如下:

<?php /** to change this template, choo tools | templates* and open the template in the editor.*/ class mongo_db { private $config; private $connection; private $db; private $connection_string; private $host; private $port; private $ur; private $pass; private $dbname; private $persist; private $persist_key; private $lects = array(); private $wheres = array(); private $sorts = array(); private $limit = 999999; private $offt = 0; private $timeout = 200; private $key = 0; /**** constructor *** automatically check if the mongo pecl extension has beeninstalled/enabled.* generate the connection string and establish a connectionto the mongodb.*/ public function __construct() { if((is_nosql != 1)){ return; } if (!class_exists('mongo')) { //$this->error("the mongodb pecl extension has not been installed or enabled", 500); } $configs =wxcity_ba::load_config("cache","mongo_db"); $num = count($configs['connect']); $this->timeout = trim($configs['timeout']); $keys = wxcity_ba::load_config('double'); $this->key = $keys['mongo_db']; $this->config = $configs['connect'][$this->key]; $status = $this->connect(); if($status == fal) { for($i = 1; $i < $num; $i++) { $n = $this->key + $i; $key = $n >= $num ? $n - $num : $n; $this->config = $configs['connect'][$key]; $status = $this->connect(); if($status!=fal) { $keys['mongo_db'] = $key ; $this->key = $key; $data = "<?php\nreturn ".var_export($keys, true).";\n?>"; file_put_contents(whty_path.'configs/double.php', $data, lock_ex); break; } } } if($status==fal) { die('mongodb not connect'); } } function __destruct() { if((is_nosql != 1)){ return; } if($this->connection) { $this->connection->clo(); } } /**** connect to mongodb  *** establish a connection to mongodb usingthe connection string generated in* the connection_string() method.if 'mongo_persist_key' was t to true in the  * config file, establish a persistent connection.we allow for only the 'persist'* option to be t becau we want to establish a connection immediately.*/ private function connect() { $this->connection_string(); $options = array('connect'=>true,'timeout'=>$this->timeout); try { $this->connection = new mongo($this->connection_string, $options); $this->db = $this->connection->{$this->dbname}; return($this); } catch (mongoconnectionexception $e) { return fal; } } /**** build connection string *** build the connection string from the config file.*/ private function connection_string() { $this->host = trim($this->config['hostname']); $this->port = trim($this->config['port']); $this->ur = trim($this->config['urname']); $this->pass = trim($this->config['password']); $this->dbname = trim($this->config['databa']); $this->persist = trim($this->config['autoconnect']); $this->persist_key = trim($this->config['mongo_persist_key']); $connection_string = "mongodb://"; if (emptyempty($this->host)) { $this->error("the host must be t to connect to mongodb", 500); } if (emptyempty($this->dbname)) { $this->error("the databa must be t to connect to mongodb", 500); } if (!emptyempty($this->ur) && !emptyempty($this->pass)) { $connection_string .= "{$this->ur}:{$this->pass}@"; } if (ist($this->port) && !emptyempty(震撼的背景音乐$this->port)) { $connection_string .= "{$this->host}:{$this->port}"; } el { $connection_string .= "{$this->host}"; } $this->connection_string = trim($connection_string); } /**** switch_db  *** switch from default databa to a different db*/ public function switch_db($databa = '') { if (emptyempty($databa)) { $this->error("to switch mongodb databas, a new databa name must be specified", 500); } $this->dbname = $databa; try { $this->db = $this->connection->{$this->dbname}; return(true); } catch (exception $e) { $this->error("unable to switch mongo databas: {$e->getmessage()}", 500); } } /**** lect fields  *** determine which fields to include or which toexclude during the query process.* currently, including and excluding at the same time is not available, so the* $includes array will take precedence overthe $excludes array.if you want to* only choo fields to exclude,leave $includes an empty array().** @usage: $this->mongo_db->lect(array('foo', 'bar'))->get('foobar');*/ public function lect($includes = array(), $excludes = array()) { if (!is_array($includes)) { $includes = array(); } if (!is_array($excludes)) { $excludes = array(); } if (!emptyempty($includes)) { foreach ($includes as $col) { $this->lects[$col] = 1; } } el { foreach ($excludes as $col) { $this->lects[$col] = 0; } } return($this); } /**** where parameters   *** get the documents bad on thearch parameters. the $wheres array should* be an associative array with the field as the key and the value as the arch* criteria.  ** @usage = $this->mongo_db->where(array('foo' => 'bar'))->get('foobar');*/ public function where($wheres = array()) { foreach ((array)$wheres as $wh => $val) { $this->wheres[$wh] = $val; } return($this); } /**** where_in parameters *** get the documents where the value of a $field is in a given $in array().** @usage = $this->mongo_db->where_in('foo', array('bar', 'zoo', 'blah'))->get('foobar');*/ public function where_in($field = "", $in = array()) { $this->where_init($field); $this->wheres[$field]['$in'] = $in; return($this); } /**** where_not_in parameters *** get the documents where the value of a $field is not in a given $in array().** @usage = $this->mongo_db->where_not_in('foo', array('bar', 'zoo', 'blah'))->get('foobar');*/ public function where_not_in($field = "", $in = array()) { $this->where_init($field); $this->wheres[$field]['$nin'] = $in; return($this); } /**** where greater than parameters  *** get the documents where the value of a $field is greater than $x* * @usage = $this->mongo_db->where_gt('foo', 20);*/ public function where_gt($field = "", $x) { $this->where_init($field); $this->wheres[$field]['$gt'] = $x; return($this); } /**** where greater than or equal to parameters  *** get the documents where the value of a $field is greater than or equal to $x** @usage = $this->mongo_db->where_gte('foo', 20);*/ public function where_gte($field = "", $x) { $this->where_init($field); $this->wheres[$field]['$gte'] = $x; return($this); } /**** where less than parameters  *** get the documents where the value ofa $field is less than $x** @usage = $this->mongo_db->where_lt('foo', 20);*/ public function where_lt($field = "", $x) { $this->where_init($field); $this->wheres[$field]['$lt'] = $x; return($this); } /**** where less than or equal to parameters  *** get the documents where the value of a $field is less than or equal to $x** @usage = $this->mongo_db->where_lte('foo', 20);*/ public function where_lte($field = "", $x) { $this->where_init($field); $this->wheres[$field]['$lte'] = $x; return($this); } /**** where between parameters   *** get the documents where the value ofa $field is between $x and $y** @usage = $this->mongo_db->where_between('foo', 20, 30);*/ public function where_between($field = "", $x, $y) { $this->where_init($field); $this->wheres[$field]['$gte'] = $x; $this->wheres[$field]['$lte'] = $y; return($this); } /**** where between and not equal to parameters  *** get the documents where the value of a $field is between but not equal to $x and $y** @usage = $this->mongo_db->where_between_ne('foo', 20, 30);*/ public function where_between_ne($field = "", $x, $y) { $this->where_init($field); $this->wheres[$field]['$gt'] = $x; $this->wheres[$field]['$lt'] = $y; return($this); } /**** where not equal to parameters  *** get the documents where the value of a $field is not equal to $x** @usage = $this->mongo_db->where_between('foo', 20, 30);*/ public function where_ne($field = "", $x) { $this->where_init($field); $this->wheres[$field]['$ne'] = $x; return($this); } /**** where or   *** get the documents where the value of a $field is in one or more values  ** @usage = $this->mongo_db->where_or('foo', array( 'foo', 'bar', 'blegh' );*/ public function where_or($field = "", $values) { $this->where_init($field); $this->wheres[$field]['$or'] = $values; return($this); } /**** where and  *** get the documents where the elements match the specified values ** @usage = $this->mongo_db->where_and( array ( 'foo' => 1, 'b' => 'someexample' );*/ public function where_and($elements_values = array()) { foreach ((array)$elements_values as $element => $val) { $this->wheres[$element] = $val; } return($this); } /**** where mod  *** get the documents where $field % $mod = $result ** @usage = $this->mongo_db->where_mod( 'foo', 10, 1 );*/ public function where_mod($field, $num, $result) { $this->where_init($field); $this->wheres[$field]['$mod'] = array($num, $result); return($this); } /**   *    *  where size *    *  *  get the documents where the size of a field is in a given $size int *  *  @usage : $this->mongo_db->where_size('foo', 1)->get('foobar'); */ public function where_size($field = "", $size = "") { $this->_where_init($field); $this->wheres[$field]['$size'] = $size; return ($this); } /**** like parameters *** get the documents where the (string) value of a $field is like a value. the defaults* allow for a ca-innsitive arch.   ** @param $flags  * allows for the typical regular expression flags:*   i = ca innsitive*   m = multiline*   x = can contain comments*   l = locale  *   s = dotall, "." matches everything, including newlines*   u = match unicode** @param $enable_start_wildcard* if t to anything other than true, a starting line character "^" will be prepended* to the arch value, reprenting only arching for a value at the start of* a new line.*  * @param $enable_end_wildcard * if t to anything other than true, an ending line character "$" will be appended* to the arch value, reprenting only arching for a value at the end of* a line.* * @usage = $this->mongo_db->like('foo', 'bar', 'im', fal, true);*/ public function like($field = "", $value = "", $flags = "i", $enable_start_wildcard = true, $enable_end_wildcard = true) { $field = (string) trim($field); $this->where_init($field); $value = (string) trim($value); $value = quotemeta($value); if ($enable_start_wildcard !== true) { $value = "^" . $value; } if ($enable_end_wildcard !== true) { $value .= "$"; } $regex = "/$value/$flags"; $this->wheres[$field] = new mongoregex($regex); return($this); } public function wheres($where){ $this->wheres = $where; } /**** order by parameters *** sort the documents bad on the parameters pasd.to t values to descending order,* you must pass values of either -1, fal,'desc', or 'desc', el they will be* t to 1 (asc).** @usage = $this->mongo_db->where_between('foo', 20, 30);*/ public function order_by($fields = array()) { if (!is_array($fields) || !count($fields)) return ; foreach ($fields as $col => $val) { if ($val == -1 || $val === fal || strtolower($val) == 金融专业排名'desc') { $this->sorts[$col] = -1; } el { $this->sorts[$col] = 1; } } return($this); } /**** limit documents *** limit the result t to $x number of documents  ** @usage = $this->mongo_db->limit($x);*/ public function limit($x = 99999) { if ($x !== null && is_numeric($x) && $x >= 1) { $this->limit = (int) $x; } return($this); } /**** offt documents   *** offt the result t to skip $x number of documents** @usage = $this->mongo_db->offt($x);*/ public function offt($x = 0) { if ($x !== null && is_numeric($x) && $x >= 1) { $this->offt = (int) $x; } return($this); } /**** get_where  **  * get the documents bad upon the pasd parameters  ** @usage = $this->mongo_db->get_where('foo', array('bar' => 'something'));*/ public function get_where($collection = "", $where = array(), $limit = 99999, $orderby=array()) { if (is_array($orderby) || !emptyempty($orderby)) { $order_by = $this->order_by($order_by); } return($this->where($where)->limit($limit)->get($collection)); } public function lecta($collection = "", $limit = 99999, $orderby=array()) { if(intval($limit)<1){ $limit = 999999; } $order_by = $this->order_by($orderby); $re = $this->limit($limit)->get($collection); $this->clear(); return (array)$re; } public function listinfo($collection = "", $orderby=array(), $page=1, $pagesize=12) { $page = max(intval($page), 1); $offt = $pagesize * ($page - 1); $pagesizes = $offt + $pagesize; $this->offt($offt); $order_by = $this->order_by($orderby); $re = $this->limit($pagesize)->get($collection); $this->limit(999999); $count = $this->count($collection); $this->pages = pages($count, $page, $pagesize); return (array)$re; } /**** get *** get the documents bad upon the pasd parameters  ** @usage = $this->mongo_db->get('foo', array('bar' => 'something'));*/ public function get($collection = "") { if (emptyempty($collection)) { $this->error("in order to retreive documents from mongodb, a collection name must be pasd", 500); } $results = array(); $documents = $this->db->{$collection}->find($this->wheres, $this->lects)->limit((int) $this->limit)->skip((int) $this->offt)->sort($this->sorts); $returns = array(); foreach ($documents as $doc): $returns[] = $doc; endforeach; return($returns); } public function getmy($collection = "") { if (emptyempty($collection)) { $this->error("in order to retreive documents from mongodb, a collection name must be pasd", 500); } $results = array(); $documents = $this->db->{$collection}->find($this->wheres, $this->lects)->limit((int) $this->limit)->skip((int) $this->offt)->sort($this->sorts); $returns = array(); foreach ($documents as $doc): $returns[] = $doc; endforeach; $this -> clear(); return($returns); } /**** count  *** count the documents bad upon the pasd parameters ** @usage = $this->mongo_db->get('foo');*/ public function count($collection = "") { if (emptyempty($collection)) { $this->error("in order to retreive a count of documents from mongodb, a collection name must be pasd", 500); } $count = $this->db->{$collection}->find($this->wheres)->limit((int) $this->limit)->skip((int) $this->offt)->count(); $this->clear(); return($count); } /**** inrt  *** inrt a new document into the pasd collection ** @usage = $this->mongo_db->inrt('foo', $data = array());*/ public function inrt($collection = "", $data = array(), $name='id') { if (emptyempty($collection)) { $this->error("no mongo collection lected to inrt into", 500); } if (count($data) == 0 || !is_array($data)) { $this->error("nothing to inrt into mongo collection or inrt is not an array", 500); } try { /**wxcity_ba::load_sys_class('whtysqs','',0); $mongoq_class = new whtysqs('creaidsqs');$re = $mongoq_class->query("?name=" . $collection . "&opt=put&data=1");**/ $re = put_sqs('list_mongo_creaidsqs','1'); if(is_numeric($re)){ $re++; $data[$name] = intval($re); }el{ $d品牌白酒ata[$name] = intval(time()); //die('mongosqs error'); } $this->db->{$collection}->inrt($data, array('fsync' => true)); $this->clear(); return $data[$name]; } catch (mongocursorexception $e) { $this->error("inrt of data into mongodb failed: {$e->getmessage()}", 500); } } public function inrtwithid($collection = "", $data = array()) { if (emptyempty($collection)) { $this->error("no mongo collection lected to inrt into", 500); } if (count($data) == 0 || !is_array($data)) { $this->error("nothing to inrt into mongo collection or inrt is not an array", 500); } try { $this->db->{$collection}->inrt($data, array('fsync' => true)); $this->clear(); return 1; } catch (mongocursorexception $e) { $this->error("inrt of data into mongodb failed: {$e->getmessage()}", 500); } } /**** update  *** update a document into the pasd collection ** @usage = $this->mongo_db->update('foo', $data = array());*/ public function update($collection = "", $data = array()) { if (emptyempty($collection)) { $this->error("no mongo collection lected 点到平面距离to update", 500); } if (count($data) == 0 || !is_array($data)) { $this->error("nothing to update in mongo collection or update is not an array", 500); } try { $this->db->{$collection}->update($this->wheres, array('$t' => $data), array('fsync' => true, 'multiple' => fal)); $this->clear(); return(true); } catch (mongocursorexception $e) { $this->error("update of data into mongodb failed: {$e->getmessage()}", 500); } } /**** update_all  *** inrt a new document into the pasd collection ** @usage = $this->mongo_db->update_all('foo', $data = array());*/ public function update_all($collection = "", $data = array()) { if (emptyempty($collection)) { $this->error("no mongo collection lected to update", 500); } if (count($data) == 0 || !is_array($data)) { $this->error("nothing to update in mongo collection or update is not an array", 500); } try { $this->db->{$collection}->update($this->wheres, array('$t' => $data), array('fsync' => true, 'multiple' => true)); return(true); } catch (mongocursorexception $e) { $this->error("update of data into mongodb failed: {$e->getmessage()}", 500); } } /**** delete  *** delete document from the pasd collection bad upon certain criteria ** @usage = $this->mongo_db->delete('foo', $data = array());*/ public function delete($collection = "") { if (emptyempty($collection)) { $this->error("no mongo collection lected to delete from", 500); } try { $this->db->{$collection}->remove($this->wheres, array('fsync' => true, 'justone' => true)); $this->clear(); return(true); } catch (mongocursorexception $e) { $this->error("delete of data into mongodb failed: {$e->getmessage()}", 500); } } /**** delete_all  *** delete all documents from the pasd collection bad upon certain criteria** @usage = $this->mongo_db->delete_all('foo', $data = array());*/ public function delete_all($collection = "") { if (emptyempty($collection)) { $this->error("no mongo collection lected to delete from", 500); } try { $this->db->{$collection}->remove($this->wheres, array('fsync' => true, 'justone' => fal)); return(true); } catch (mongocursorexception $e) { $this->error("delete of data into mongodb failed: {$e->getmessage()}", 500); } } /**** add_index  *** ensure an index of the keys in a collection with optional parameters.to t values to descending order,* you must pass values of either -1, fal, 'desc', or 'desc', el they will be* t to 1 (asc). ** @usage = $this->mongo_db->add_index($collection, array('first_name' => 'asc', 'last_name' => -1), array('unique' => true));*/ public function add_index($collection = "", $keys = array(), $options = array()) { if (emptyempty($collection)) { $this->error("no mongo collection specified to add index to", 500); } if (emptyempty($keys) || !is_array($keys)) { $this->error("index could not be created to mongodb collection becau no keys were specified", 500); } foreach ($keys as $col => $val) { if ($val == -1 || $val === fal || strtolower($val) == 'desc') { $keys[$col] = -1; } el { $keys[$col] = 1; } } if ($this->db->{$collection}->ensureindex($keys, $options) == true) { $this->clear(); return($this); } el { $this->error("an error occured when trying to add an index to mongodb collection", 500); } } /**** remove_index   *** remove an index of the keys in a collection.to t values to descending order,* you must pass values of either -1, fal, 'desc', or 'desc', el they will be* t to 1 (asc). ** @usage = $this->mongo_db->remove_index($collection, array('first_name' => 'asc', 'last_name' => -1));*/ public function remove_index($collection = "", $keys = array()) { if (emptyempty($collection)) { $this->error("no mongo collection specified to remove index from", 500); } if (emptyempty($keys) || !is_array($keys)) { $this->error("index could not be removed from mongodb collection becau no keys were specified", 500); } if ($this->db->{$collection}->deleteindex($keys, $options) == true) { $this->clear(); return($this); } el { $this->error("an error occured when trying to remove an index from mongodb collection", 500); } } /**** remove_all_indexes  *** remove all indexes from a collection. ** @us我的世界地图编辑器age = $this->mongo_db->remove_all_index($collection);*/ public function remove_all_indexes($collection = "") { if (emptyempty($collection)) { $this->error("no mongo collection specified to remove all indexes from", 500); } $this->db->{$collection}->deleteindexes(); $this->clear(); return($this); } /**** list_indexes   *** lists all indexes in a collection. ** @usage = $this->mongo_db->list_indexes($collection);*/ public function list_indexes($collection = "") { if (emptyempty($collection)) { $this->error("no mongo collection specified to remove all indexes from", 500); } return($this->db->{$collection}->getindexinfo()); } /**** drop collection *** removes the specified collection from the databa.be careful becau this* can have some very large issues in production!*/ public function drop_collection($collection = "") { if (emptyempty($collection)) { $this->error("no mongo collection specified to drop from databa", 500); } $this->db->{$collection}->drop(); return true; } /**** clear  *** rets the class variables to default ttings*/ private function clear() { $this->lects = array(); $this->wheres = array(); $this->limit = null; $this->offt = null; $this->sorts = array(); } /**** where initializer  *** prepares parameters for inrtion in $wheres array().*/ private function where_init($param) { if (!ist($this->wheres[$param])) { $this->wheres[$param] = array(); } } public function error($str, $t) { echo $str; exit; } } ?>

使用范例:

$table_name=trim(strtolower($this->table_name)); $this->mongo_db->where($where); $order=!emptyempty($order)?array('aid'=>'desc'):array('aid'=>'asc');//升序降序 $infos=$this->mongo_db->listinfo($table_name,$order,$page,$pagesize);

希望本文所述对大家的php程序设计有所帮助。

本文发布于:2023-04-06 09:16:16,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/3cb021264b903b99c3e9f3b2d8681c52.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:php实现的mongodb操作类实例.doc

本文 PDF 下载地址:php实现的mongodb操作类实例.pdf

标签:本文   升序   给大家   世界地图
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图