백엔드 개발 PHP 튜토리얼 PHP로 캡슐화된 mongodb 작업 클래스

PHP로 캡슐화된 mongodb 작업 클래스

Jul 25, 2016 am 08:43 AM

  1. /*
  2. * 이 템플릿을 변경하려면 도구 | 템플릿
  3. * 편집기에서 템플릿을 엽니다.
  4. */
  5. class mongo_db {
  6. private $config;
  7. 비공개 $connection;
  8. 비공개 $db;
  9. 비공개 $connection_string;
  10. 비공개 $host;
  11. 비공개 $port;
  12. 개인 $user;
  13. 비공개 $pass;
  14. 비공개 $dbname;
  15. 비공개 $persist;
  16. 비공개 $persist_key;
  17. 비공개 $selects = array();
  18. 비공개 $wheres = array();
  19. 비공개 $sorts = array();
  20. 비공개 $limit = 999999;
  21. 비공개 $offset = 0;
  22. 비공개 $timeout = 200;
  23. 개인 $key = 0;
  24. /*** ------------------------------------------------- ------------------ * 생성자 * --- ------------------------------------- -------------- * * Mongo PECL 확장이 설치/활성화되었는지 자동으로 확인합니다. * 연결 문자열을 생성하고 MongoDB에 대한 연결을 설정합니다.*/
  25. 공개 함수 __construct() {
  26. if((IS_NOSQL != 1)){
  27. return;
  28. }
  29. if (!class_exists('Mongo')) {
  30. //$this->error("MongoDB PECL 확장이 설치되지 않았거나 활성화되지 않았습니다.", 500);
  31. }
  32. $configs =wxcity_base::load_config("캐시","mongo_db");
  33. $num = count($configs['connect']);
  34. $this->timeout = Trim($configs['timeout']);
  35. $keys = wxcity_base::load_config('double');
  36. $this->key = $keys['mongo_db'];
  37. $this->config = $configs['connect'][$this->key];
  38. $status = $this->connect();
  39. if($status == false)
  40. {
  41. for($i = 1; $i < $num; $i )
  42. {
  43. $n = $this-> 키 $i;
  44. $key = $n >= $num ? $n - $번호 : $n;
  45. $this->config = $configs['connect'][$key];
  46. $status = $this->connect();
  47. if($status!=false)
  48. {
  49. $keys['mongo_db'] = $key ;
  50. $this->key = $key;
  51. $data = "";
  52. file_put_contents(WHTY_PATH.'configs/double.php', $data, LOCK_EX);
  53. 휴식;
  54. }
  55. }
  56. }
  57. if($status==false)
  58. {
  59. die('mongoDB가 연결되지 않음');
  60. }
  61. }
  62. function __destruct() {
  63. if((IS_NOSQL != 1)){
  64. return;
  65. }
  66. if($this->connection)
  67. {
  68. $this->connection->close();
  69. }
  70. }
  71. /*** ------------------------------------------------- ------------------ * MONGODB에 연결 * -------------- ------------------------------------- ---------------- * * * Connection_string() 메소드에서 생성된 연결 문자열을 사용하여 MongoDB에 대한 연결을 설정합니다. * 구성 파일에서 'mongo_persist_key'가 true로 설정된 경우 영구 연결을 설정합니다. 즉시 연결을 설정하려고 하기 때문에 'persist' * 옵션만 설정하도록 허용합니다.*/
  72. private function connect() {
  73. $this->connection_string();
  74. $options = array('connect'=>true,'timeout'=>$this->timeout);
  75. try {
  76. $this->connection = new Mongo($this->connection_string, $options);
  77. $this->db = $this->connection->{$this->dbname};
  78. return($this);
  79. } catch(MongoConnectionException $e) {
  80. return false;
  81. }
  82. }
  83. /*** ------------------------------------------------- ------------------------------- * 建構連接字串* ------------- ------------------------------------------------- - ---------------- * * 從設定檔建立連接字串。*/
  84. private function connection_string() {
  85. $this->host = trim($this->config['hostname']);
  86. $this->port = trim($this->config['port']);
  87. $this->user = trim($this->config['使用者名稱']);
  88. $this->pass = trim($this->config['password']);
  89. $this->dbname = trim($this->config['database']);
  90. $this->persist = trim($this->config['autoconnect']);
  91. $this->persist_key = trim($this->config['mongo_persist_key']);
  92. $connection_string = "mongodb://";
  93. if (emptyempty($this->host)) {
  94. $this->error("必須將主機設定為連接到 MongoDB", 500);
  95. } if (emptyempty($this->dbname)) {
  96. $this->error("資料庫必須設定為連接到 MongoDB", 500);
  97. } if (!emptyempty($this->user) && !emptyempty($this->pass)) {
  98. $connection_string .= "{$this->user}:{$this->透過} @”;
  99. } if (isset($this->port) && !emptyempty($this->port)) {
  100. $connection_string .= "{$this->host}:{$this-> ;港口} 」;
  101. } else {
  102. $connection_string .= "{$this->host}";
  103. } $this->connection_string = trim($connection_string); > /*** ------------------------------------------------- ------------------------------- * Switch_db * ---------------- -------------------------------------------------- -------------- * * 從預設資料庫切換到不同的資料庫*/
  104. public function switch_db($database = '') {
  105. if (emptyempty($database)) {
  106. $this- >error(" 切換MongoDB資料庫,必須指定新的資料庫名稱", 500) ;
  107. } $this->dbname = $database;
  108. 嘗試{
  109. $this->db = $this->connection->{$this->dbname };
  110. 回傳(真) ;
  111. } catch (Exception $e) {
  112. $this->error(" 無法切換Mongo 資料庫:{$e->getMessage()}", 500);
  113. }
  114. }
  115. /*** ------------------------------------------------- ------------------------------- * 選擇欄位* --------------- -------------------------------------------------- --------------- * * 決定在查詢過程中包含哪些欄位或排除哪些欄位。 * 目前,不能同時包含和排除,因此 * $includes 陣列將優先於 $excludes 陣列。 如果您只想選擇要排除的字段,請將 $includes 保留為空 array()。 * * @usage: $this->mongo_db->select(array('foo', 'bar'))->get('foobar');*/
  116. public function select($includes = array(), $excludes = array()) {
  117. if (! is_array($includes)) {
  118. $includes = array()
  119. }
  120. if (!is_array($excludes)) {
  121. $excludes = array()
  122. } if (!emptyempty($includes)) {
  123. foreach ($includes as $col) {
  124. $this->selects[$col] = 1;
  125. }
  126. } else {
  127. foreach ($excludes as $col) {
  128. $this->selects[$col] = 0;
  129. }
  130. } return($this);
  131. }
  132. /*** ------------------------------------------------- ------------------------------- * 參數所在* --------------- -------------------------------------------------- ---------------- * * 根據這些搜尋參數取得文件。 $wheres 數組應該是一個關聯數組,其中字段作為鍵,值作為搜尋條件。 * * @usage = $this->mongo_db->where(array('foo' => 'bar'))->get('foobar');*/
  133. public function where($wheres = array()) {
  134. foreach ((array)$wheres as $wh => $ val ) {
  135. $this->wheres[$wh] = $val;
  136. } return($this);
  137. }
  138. /*** ------------------------------------------------- ------------------ * WHERE_IN 매개변수 * --------------- ------------------------------------- --------------- * * $field의 값이 주어진 $in array()에 있는 문서를 가져옵니다. * * @usage = $this->mongo_db->where_in('foo', array('bar', 'zoo', 'blah'))->get('foobar');*/
  139. 공용 함수 where_in($field = "", $in = array()) {
  140. $this->where_init($field);
  141. $this->wheres[$field]['$in'] = $in;
  142. return($this);
  143. }
  144. /*** ------------------------------------------------- ------------------ * WHERE_NOT_IN 매개변수 * --------------- ------------------------------------- --------------- * * $field의 값이 주어진 $in array()에 없는 문서를 가져옵니다. * * @usage = $this->mongo_db->where_not_in('foo', array('bar', 'zoo', 'blah'))->get('foobar');*/
  145. 공개 함수 where_not_in($field = "", $in = array()) {
  146. $this->where_init($ 필드);
  147. $this->wheres[$field]['$nin'] = $in;
  148. return($this);
  149. }
  150. /*** ------------------------------------------------- ------------------ * 매개변수보다 큰 경우 * ------------- ------------------------------------- ----------------- * * $field의 값이 $x보다 큰 문서 가져오기 * * @usage = $this->mongo_db->where_gt( '푸', 20);*/
  151. 공개 함수 where_gt($field = "", $x) {
  152. $this->where_init($field);
  153. $this->wheres[$field]['$gt'] = $x;
  154. return($this);
  155. }
  156. /*** ------------------------------------------------- ------------------ * 매개변수보다 크거나 같은 경우 * ---------- ------------------------------------- ------- * * $field의 값이 $x보다 크거나 같은 문서를 가져옵니다. * * @usage = $this-> mongo_db->where_gte('foo', 20);*/
  157. 공개 함수 where_gte($field = "", $x) {
  158. $this->where_init($field);
  159. $this->wheres[$field]['$gte'] = $x;
  160. return($this);
  161. }
  162. /*** ------------------------------------------------- ------------------ * 매개변수보다 작은 경우 * ------------- ------------------------------------- ----------------- * * $field의 값이 $x보다 작은 문서 가져오기 * * @usage = $this->mongo_db->where_lt( '푸', 20);*/
  163. 공개 함수 where_lt($field = "", $x) {
  164. $this->where_init($field);
  165. $this->wheres[$field]['$lt'] = $x;
  166. return($this);
  167. }
  168. /*** ------------------------------------------------- ------------------ * 매개변수보다 작거나 같은 경우 * ---------- ------------------------------------- ------- * * $field의 값이 $x보다 작거나 같은 문서 가져오기 * * @usage = $this-> mongo_db->where_lte('foo', 20);*/
  169. 공개 함수 where_lte($field = "", $x) {
  170. $this->where_init($field);
  171. $this->wheres[$field]['$lte'] = $x;
  172. return($this);
  173. }
  174. /*** ------------------------------------------------- ------------------ * 매개변수 사이 * -------------- ------------------------------------- ---------------- * * $field의 값이 $x와 $y 사이에 있는 문서 가져오기 * * @usage = $this->mongo_db->where_between ('푸', 20, 30);*/
  175. 공개 함수 where_between($field = "", $x, $y) {
  176. $this->where_init($field );
  177. $this->wheres[$field]['$gte'] = $x;
  178. $this->wheres[$field]['$lte'] = $y;
  179. return($this);
  180. }
  181. /*** ------------------------------------------------- ------------------ * 매개변수 사이 및 매개변수와 같지 않음 * ---------- ------------------------------------- ------- * * $field의 값이 $x와 $y 사이이지만 같지 않은 문서를 가져옵니다. * * @usage = $this ->mongo_db->where_between_ne('foo', 20, 30);*/
  182. 공개 함수 where_between_ne($field = "", $x, $y) {
  183. $this->where_init($field);
  184. $this->wheres[$field]['$gt'] = $x;
  185. $this->wheres[$field]['$lt'] = $y;
  186. return($this);
  187. }
  188. /*** ------------------------------------------------- ------------------ * 매개변수와 같지 않은 경우 * ------------ ------------------------------------- ------------------ * * $field의 값이 $x와 같지 않은 문서를 가져옵니다. * * @usage = $this->mongo_db-> where_between('foo', 20, 30);*/
  189. 공개 함수 where_ne($field = "", $x) {
  190. $this->where_init($field);
  191. $this->wheres[$field]['$ne'] = $x;
  192. return($this);
  193. }
  194. /*** ------------------------------------------------- ------------------ * 어디서 또는 * --------------- ------------------------------------- --------------- * * $field의 값이 하나 이상의 값에 있는 문서 가져오기 * * @usage = $this->mongo_db->where_or(' foo', array( 'foo', 'bar', 'blegh' );*/
  195. 공개 함수 where_or($field = "", $values) {
  196. $this->where_init($field);
  197. $this->wheres[$field]['$or'] = $values;
  198. return($this);
  199. }
  200. /*** ------------------------------------------------- ------------------ * 어디서 그리고 * --------------- ------------------------------------- --------------- * * 요소가 지정된 값과 일치하는 문서 가져오기 * * @usage = $this->mongo_db->where_and( array ( 'foo' => ; 1, 'b' => '일부 예' );*/
  201. 공개 함수 where_and($elements_values ​​= array()) {
  202. foreach ((array)$elements_values ​​as $element => $ val) {
  203. $this->wheres[$element] = $val;
  204. } return($this);
  205. }
  206. /*** ------------------------------------------------- ------------------ * MOD는 어디에 * --------------- ------------------------------------- --------------- * * $field % $mod = $result * * @usage = $this->mongo_db->where_mod( 'foo', 10 있는 문서 가져오기 , 1 );*/
  207. 공개 함수 where_mod($field, $num, $result) {
  208. $this->where_init($field);
  209. $this->wheres[$field]['$mod'] = array($num, $result);
  210. return($this);
  211. }
  212. /*** ------------------------------------------------- ------------------ * 사이즈는 * --------------- ------------------------------------- --------------- * * 필드 크기가 지정된 $size int인 문서 가져오기 * * @usage : $this->mongo_db->where_size(' foo', 1)->get('foobar');*/
  213. 공개 함수 where_size($field = "", $size = "") {
  214. $this->_where_init($field );
  215. $this->wheres[$field]['$size'] = $size;
  216. 반환($this);
  217. }
  218. /*** ------------------------------------------------- ------------------------------- * 類似參數 * --------------- -------------------------------------------------- --------------- * * 取得$field 的(字串)值類似值的文件。預設值 * 允許不區分大小寫的搜尋。 * * @param $flags * 允許典型的正規表示式標誌: * i = 不區分大小寫* m = 多行* x = 可以包含註解* l = 區域設定* s = dotall, "."符合所有內容,包括換行符* u = 匹配unicode * * @param $enable_start_wildcard * 如果設定為TRUE 以外的任何內容,則在搜尋值前面新增起始行字元“^”,表示僅搜尋開頭處的值* 一新行。 * * @param $enable_end_wildcard * 如果設定為 TRUE 以外的任何值,則結束行字元「$」將附加到搜尋值,表示僅搜尋行末尾的值。 * * @usage = $this->mongo_db->like('foo', 'bar', 'im', FALSE, TRUE);*/
  219. 公用函數如($field = "", $value = "", $flags = "i", $enable_start_wildcard = TRUE, $enable_end_wildcard = TRUE) {
  220. $field = (string) 修剪($field);
  221. $this->where_init($field);
  222. $值 = (字串) 修剪($值);
  223. $value = quotemeta($value);
  224. if ($enable_start_wildcard !== TRUE) {
  225. $value = "^" . $值;
  226. } if ($enable_end_wildcard !== TRUE) {
  227. $value .= "$";
  228. } $regex = "/$value/$flags";
  229. $this->wheres[$field] = new MongoRegex($regex);
  230. 返回($this);
  231. }
  232. public function wheres($where){
  233. $this->wheres = $where;
  234. }
  235. /*** ------------------------------------------------- ------------------------------- * 依參數排序 * -------------- -------------------------------------------------- ---------------- * * 根據傳遞的參數對文件進行排序。若要將值設為降序,* 您必須傳遞 -1、FALSE、'desc' 或 'DESC' 值,否則它們將被 * 設定為 1 (ASC)。 * * @usage = $this->mongo_db->where_ Between('foo', 20, 30);*/
  236. public function order_by($fields = array()) {
  237. if (!is_array($fields) || !count($ ) ) 欄位))回傳;
  238. foreach ($fields as $col => $val) {
  239. if ($val == -1 || $val === FALSE || strtolower($val) = = 'desc') {
  240. $this->sorts[$col] = -1; } else {
  241. $this->sorts[$col] = 1;
  242. }
  243. } return( $this); }
  244. /*** ------------------------------------------------- ------------------------------- * 限製檔案* --------------- -------------------------------------------------- --------------- * * 將結果集限制為$x 個文件* * @usage = $this->mongo_db->limit($x);*/
  245. 公用函數limit($x = 99999) {
  246. if ($x !== NULL && is_numeric ($x) && $ x >= 1) {
  247. $this->limit = (int) $x;
  248. } return($this); }
  249. /** * ------------------------------------------------- ------------------------------- * 抵銷文件 * --------------- -------------------------------------------------- --------------- * * 偏移結果集以跳過$x 個文件* * @usage = $this->mongo_db->offset($x);*/
  250. public function offset($x = 0) {
  251. if ($x !== NULL && is_numeric($x) && $ x >= 1) {
  252. $this-> offset = (int) $x;
  253. } return($this)
  254. }
  255. /*** ------------------------------------------------- ------------------------------------------- * 到達地點 * --- ------------- ------------------------------------- ------------- -------------- * * 根據傳入的參數取得文件* * @usage = $this->mongo_db->get_where( 'foo', array('bar' = >「某事」));*/
  256. public function get_where($collection = "", $ where = array(), $limit = 99999, $orderby=array()) {
  257. if (is_array($orderby) || !emptyempty($orderby)) {
  258. $order_by = $this->order_by ($order_by);
  259. }
  260. return($this->where($where)->limit($limit)->get($collection));
  261. }
  262. public function selectA( $collection = "", $limit = 99999, $orderby=array()) {
  263. if(intval($limit) $limit = 999999;
  264. }
  265. $order_by = $this->order_by($orderby);
  266. $re = $this->limit($limit)->get($collection);
  267. $this->clear();
  268. return (배열)$re;
  269. }
  270. 공개 함수 listinfo($collection = "", $orderby=array(), $page=1, $pagesize=12) {
  271. $page = max(intval($page) ), 1);
  272. $offset = $pagesize * ($page - 1);
  273. $pagesizes = $offset $pagesize;
  274. $this->offset($offset);
  275. $order_by = $this->order_by($orderby);
  276. $re = $this->limit($pagesize)->get($collection);
  277. $this->limit(999999);
  278. $count = $this->count($collection);
  279. $this->pages = 페이지($count, $page, $pagesize);
  280. return (배열)$re;
  281. }
  282. /*** ------------------------------------------------- ------------------------------- * 얻다 * ---------------- ------------------------------------- -------------- * * 전달된 매개변수를 기반으로 문서 가져오기 * * @usage = $this->mongo_db->get('foo', array('bar' = > '뭔가'));*/
  283. 공개 함수 get($collection = "") {
  284. if (emptyempty($collection)) {
  285. $this- >error("MongoDB에서 문서를 검색하려면 컬렉션 이름을 전달해야 합니다.", 500);
  286. } $결과 = 배열();
  287. $documents = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int) $this-> ;limit)->skip((int) $this->offset)->sort($this->sorts);
  288. $returns = 배열();
  289. foreach($documents를 $doc로): $returns[] = $doc;
  290. endforeach;
  291. 반환($returns);
  292. }
  293. public function getMy($collection = "") {
  294. if (emptyempty($collection)) {
  295. $this->error("다음에서 문서를 검색하려면 MongoDB, 컬렉션 이름을 전달해야 합니다.", 500);
  296. } $결과 = 배열();
  297. $documents = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int) $this-> ;limit)->skip((int) $this->offset)->sort($this->sorts);
  298. $returns = 배열();
  299. foreach($documents를 $doc로): $returns[] = $doc;
  300. endforeach;
  301. $이것 -> 분명한();
  302. 반환($returns);
  303. }
  304. /*** ------------------------------------------------- ------------------------------- * 세다 * ---------------- ------------------------------------- -------------- * * 전달된 매개변수를 기반으로 문서 개수 * * @usage = $this->mongo_db->get('foo');*/
  305. 공개 함수 개수($collection = "") {
  306. if (emptyempty($collection)) {
  307. $this- >error("MongoDB에서 문서 개수를 검색하려면 컬렉션 이름을 전달해야 합니다.", 500);
  308. } $count = $this->db->{$collection}->find($this->wheres)->limit((int) $this->limit)-> Skip((int) $this->offset)->count();
  309. $this->clear();
  310. 반환($count);
  311. }
  312. /*** ------------------------------------------------- ------------------ * 삽입 * --- ------------------------------------- -------------- * * 전달된 컬렉션에 새 문서 삽입 * * @usage = $this->mongo_db->insert('foo', $data = array() );*/
  313. 공개 함수 insert($collection = "", $data = array(), $name='ID') {
  314. if (emptyempty($collection)) {
  315. $this->error("삽입할 Mongo 컬렉션을 선택하지 않았습니다.", 500);
  316. } if (count($data) == 0 || !is_array($data)) {
  317. $this->error("Mongo 컬렉션에 삽입할 항목이 없거나 삽입할 항목이 배열이 아닙니다.", 500 );
  318. } try {
  319. /**
  320. wxcity_base::load_sys_class('whtysqs','',0);
  321. $mongoseq_class = new whtysqs('creaseidsqs');
  322. $re = $mongoseq_class->query("?name=" . $collection . "&opt=put&data=1");
  323. **/
  324. $re = put_sqs('list_mongo_creaseidsqs','1');
  325. if(is_numeric($re)){
  326. $re ;
  327. $data[$name] = intval($re);
  328. }else{
  329. $data[$name] = intval(time());
  330. //die('mongosqs 오류');
  331. }
  332. $this->db->{$collection}->插入($data, array('fsync' => TRUE));
  333. $this->clear();
  334. 回傳$data[$name];
  335. } catch (MongoCursorException $e) {
  336. $this->error("將資料插入MongoDB 失敗:{$e->getMessage()}", 500);
  337. }
  338. }
  339. public function insertWithId($ collection = "", $data = array()) {
  340. if (emptyempty($collection)) {
  341. $this- >error("沒有選擇要插入的Mongo 集合", 500);
  342. } if (count($data) == 0 || !is_array($data)) {
  343. $this->error("Nothing to insert into Mongo collection or insert is not an array", 500 );
  344. } try {
  345. $this->db->{$collection}->insert($data, array('fsync' => TRUE));
  346. $this->clear();
  347. 回傳1;
  348. } catch (MongoCursorException $e) {
  349. $this->error("將資料插入MongoDB 失敗:{$e->getMessage()}", 500);
  350. }
  351. }
  352. /*** ------------------------------------------------- - - - - - - - - - - - - - - - - * 更新* - - - - - - - - ----------------------- --------------------------- -------------- * * 將文件更新到傳遞的集合中* * @usage = $this->mongo_db->update('foo', $data = array()) ;*/
  353. public function update($collection = "", $data = array()) {
  354. if (emptyempty($collection) ) {
  355. $ this->error("沒有選擇要更新的Mongo 集合", 500);
  356. } if (count($data) == 0 || !is_array($data)) {
  357. $this->error ("Mongo 集合中沒有要更新的內容或更新不是陣列", 500 );
  358. } try {
  359. $this->db->{$collection}->update($this->wheres, array ('$set' => $data), array(' fsync' => TRUE,'多個' => FALSE));
  360. $this->clear();
  361. 回傳(真);
  362. } catch (MongoCursorException $e) {
  363. $this->error("將資料更新至MongoDB 失敗:{$e->getMessage()}", 500);
  364. }
  365. }
  366. /*** ------------------------------------------------- ------------------------------- * UPDATE_ALL * ---------------- -------------------------------------------------- -------------- * * 將新文件插入傳遞的集合* * @usage = $this->mongo_db->update_all('foo', $data = array() ) ;*/
  367. public function update_all($collection = "", $data = array()) {
  368. if (emptyempty( $collection)) {
  369. $ this->error("沒有選擇要更新的Mongo 集合", 500);
  370. } if (count($data) == 0 || !is_array($data)) {
  371. $this->error ("Mongo 集合中沒有要更新的內容或更新不是陣列", 500 );
  372. } try {
  373. $this->db->{$collection}->update($this->wheres, array ('$set' => $data), array(' fsync' => TRUE, '多個' => TRUE);
  374. 回傳(真);
  375. } catch (MongoCursorException $e) {
  376. $this->error("將資料更新至MongoDB 失敗:{$e->getMessage()}", 500);
  377. }
  378. }
  379. /*** ------------------------------------------------- - - - - - - - - - - - - - - - - * 刪除* - - - - - - - - ----------------------- --------------------------- -------------- * * 依特定條件從傳遞的集合中刪除文件* * @usage = $this->mongo_db->delete('foo', $data = array ());* /
  380. public function delete($collection = "") {
  381. if (emptyempty($collection)) {
  382. $this->error("沒有選擇要刪除的Mongo 集合", 500);
  383. } try {
  384. $this->db->{$collection}->remove($this->wheres, array('fsync' => TRUE, 'justOne' =>;真的));
  385. $this->clear();
  386. 回傳(真);
  387. } catch (MongoCursorException $e) {
  388. $this->error("刪除MongoDB 資料失敗:{$e->getMessage ()}", 500);
  389. }
  390. }
  391. /*** ------------------------------------------------- ------------------ * DELETE_ALL * --- ------------------------------------- -------------- * * 특정 기준에 따라 전달된 컬렉션에서 모든 문서 삭제 * * @usage = $this->mongo_db->delete_all('foo', $data = 정렬());*/
  392. public function delete_all($collection = "") {
  393. if (emptyempty($collection)) {
  394. $this->error( "삭제할 Mongo 컬렉션이 선택되지 않았습니다.", 500);
  395. } try {
  396. $this->db->{$collection}->remove($this->wheres, array('fsync' => TRUE, 'justOne' => 거짓));
  397. 반환(TRUE);
  398. } catch (MongoCursorException $e) {
  399. $this->error("MongoDB로의 데이터 삭제 실패: {$e->getMessage()}", 500);
  400. }
  401. }
  402. /*** ------------------------------------------------- ------------------ * ADD_INDEX * --- ------------------------------------- -------------- * * 선택적 매개변수를 사용하여 컬렉션의 키 인덱스를 확인합니다. 값을 내림차순으로 설정하려면 * -1, FALSE, 'desc' 또는 'DESC' 값을 전달해야 합니다. 그렇지 않으면 * 1(ASC)로 설정됩니다. * * @usage = $this->mongo_db->add_index($collection, array('first_name' => 'ASC', 'last_name' => -1), array('unique' => TRUE )));*/
  403. 공개 함수 add_index($collection = "", $keys = array(), $options = array()) {
  404. if (emptyempty($collection)) {
  405. $this->error("인덱스를 추가할 Mongo 컬렉션이 지정되지 않았습니다.", 500);
  406. } if (emptyempty($keys) || !is_array($keys)) {
  407. $this->error("키가 지정되지 않았기 때문에 MongoDB 컬렉션에 인덱스를 생성할 수 없습니다.", 500);
  408. } foreach ($keys as $col => $val) {
  409. if ($val == -1 || $val === FALSE || strtolower($val) == 'desc') {
  410. $keys[$col] = -1;
  411. } else {
  412. $keys[$col] = 1;
  413. }
  414. } if ($this->db->{$collection}->ensureIndex($keys, $options) == TRUE) {
  415. $this->clear() ;
  416. return($this);
  417. } else {
  418. $this->error("MongoDB 컬렉션에 인덱스를 추가하려고 할 때 오류가 발생했습니다.", 500);
  419. }
  420. }
  421. /*** ------------------------------------------------- ------------------ * REMOVE_INDEX * --- ------------------------------------- -------------- * * 컬렉션에 있는 키의 인덱스를 제거합니다. 값을 내림차순으로 설정하려면 * -1, FALSE, 'desc' 또는 'DESC' 값을 전달해야 합니다. 그렇지 않으면 * 1(ASC)로 설정됩니다. * * @usage = $this->mongo_db->remove_index($collection, array('first_name' => 'ASC', 'last_name' => -1));*/
  422. 공개 함수 Remove_index($collection = "", $keys = array()) {
  423. if (emptyempty( $collection)) {
  424. $this->error("인덱스를 제거할 Mongo 컬렉션이 지정되지 않았습니다.", 500);
  425. } if (emptyempty($keys) || !is_array($keys)) {
  426. $this->error("지정된 키가 없기 때문에 MongoDB 컬렉션에서 인덱스를 제거할 수 없습니다.", 500);
  427. } if ($this->db->{$collection}->deleteIndex($keys, $options) == TRUE) {
  428. $this->clear();
  429. return($this);
  430. } else {
  431. $this->error("MongoDB 컬렉션에서 인덱스를 제거하려고 할 때 오류가 발생했습니다.", 500);
  432. }
  433. }
  434. /*** ------------------------------------------------- ------------------ * REMOVE_ALL_INDEXES * --- ------------------------------------- -------------- * * 컬렉션에서 모든 인덱스를 제거합니다. * * @usage = $this->mongo_db->remove_all_index($collection);*/
  435. 공개 함수 Remove_all_indexes($collection = "") {
  436. if (emptyempty($collection)) {
  437. $this->error("모든 인덱스를 제거하기 위해 지정된 Mongo 컬렉션이 없습니다.", 500);
  438. } $this->db->{$collection}->deleteIndexes();
  439. $this->clear();
  440. return($this);
  441. }
  442. /*** ------------------------------------------------- ------------------------------- * LIST_INDEXES * ---------------- -------------------------------------------------- -------------- * * 列出集合中的所有索引。 * * @usage = $this->mongo_db->list_indexes($collection);*/
  443. public function list_indexes($collection = "") {
  444. if (emptyempty($collection)) {
  445. $this->error( “沒有指定要從中刪除所有索引的Mongo 集合」, 500);
  446. } return($this->db->{$collection}->getIndexInfo());
  447. }
  448. / *** ------------------------------------------------- ------------------------------- * 刪除收藏 * --------------- -------------------------------------------------- --------------- * * 從資料庫中刪除指定的集合。 請小心,因為這 * 在生產中可能會出現一些非常大的問題!*/
  449. public function drop_collection($collection = "") {
  450. if (emptyempty($collection)) {
  451. $this- >錯誤(「沒有指定從資料庫中刪除的Mongo 集合」, 500);
  452. } $this->db->{$collection}->drop();
  453. 回傳TRUE;
  454. }
  455. /*** ------------------------------------------------- - - - - - - - - - - - - - - - - * 清除* - - - - - - - - ----------------------- --------------------------- -------------- * * 將類別變數重設為默認設定 */
  456. private function clear() {
  457. $this->selects = array();
  458. $this->wheres = array();
  459. $this->limit = NULL;
  460. $this->offset = NULL;
  461. $this->sorts = array();
  462. }
  463. /*** ------------------------------------------------- ------------------------------- * 初始化器所在位置* ------------- -- ------------------------------------------------ -- --------------- * * 準備參數以插入$wheres array() 中。*/
  464. private function where_init($param) {
  465. if (!isset($this->wheres[$param])) {
  466. $this->wheres[$param] = array();
  467. }
  468. }
  469. 公用函數錯誤($str, $t) {
  470. echo $str;
  471. 退出;
  472. }
  473. }
  474. ? >
複製程式碼

使用範例
  1. $table_name=trim(strtolower($this->table_name));
  2. $this->mongo_db->where($where);
  3. $this->mongo_db->where($where);
  4. $order=!emptyempty($order)?array('AID'=>'DESC'):array('AID'=>'ASC');//升序降序
$infos=$ this->mongo_db ->listinfo($table_name,$order,$page,$pagesize);
複製程式碼

PHP、MongoDB


본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

JWT (JSON Web Tokens) 및 PHP API의 사용 사례를 설명하십시오. JWT (JSON Web Tokens) 및 PHP API의 사용 사례를 설명하십시오. Apr 05, 2025 am 12:04 AM

JWT는 주로 신분증 인증 및 정보 교환을 위해 당사자간에 정보를 안전하게 전송하는 데 사용되는 JSON을 기반으로 한 개방형 표준입니다. 1. JWT는 헤더, 페이로드 및 서명의 세 부분으로 구성됩니다. 2. JWT의 작업 원칙에는 세 가지 단계가 포함됩니다. JWT 생성, JWT 확인 및 Parsing Payload. 3. PHP에서 인증에 JWT를 사용하면 JWT를 생성하고 확인할 수 있으며 사용자 역할 및 권한 정보가 고급 사용에 포함될 수 있습니다. 4. 일반적인 오류에는 서명 검증 실패, 토큰 만료 및 대형 페이로드가 포함됩니다. 디버깅 기술에는 디버깅 도구 및 로깅 사용이 포함됩니다. 5. 성능 최적화 및 모범 사례에는 적절한 시그니처 알고리즘 사용, 타당성 기간 설정 합리적,

확실한 원칙과 PHP 개발에 적용되는 방법을 설명하십시오. 확실한 원칙과 PHP 개발에 적용되는 방법을 설명하십시오. Apr 03, 2025 am 12:04 AM

PHP 개발에서 견고한 원칙의 적용에는 다음이 포함됩니다. 1. 단일 책임 원칙 (SRP) : 각 클래스는 하나의 기능 만 담당합니다. 2. Open and Close Principle (OCP) : 변경은 수정보다는 확장을 통해 달성됩니다. 3. Lisch의 대체 원칙 (LSP) : 서브 클래스는 프로그램 정확도에 영향을 미치지 않고 기본 클래스를 대체 할 수 있습니다. 4. 인터페이스 격리 원리 (ISP) : 의존성 및 사용되지 않은 방법을 피하기 위해 세밀한 인터페이스를 사용하십시오. 5. 의존성 반전 원리 (DIP) : 높고 낮은 수준의 모듈은 추상화에 의존하며 종속성 주입을 통해 구현됩니다.

시스템 재시작 후 UnixSocket의 권한을 자동으로 설정하는 방법은 무엇입니까? 시스템 재시작 후 UnixSocket의 권한을 자동으로 설정하는 방법은 무엇입니까? Mar 31, 2025 pm 11:54 PM

시스템이 다시 시작된 후 UnixSocket의 권한을 자동으로 설정하는 방법. 시스템이 다시 시작될 때마다 UnixSocket의 권한을 수정하려면 다음 명령을 실행해야합니다.

PHP에서 늦은 정적 결합의 개념을 설명하십시오. PHP에서 늦은 정적 결합의 개념을 설명하십시오. Mar 21, 2025 pm 01:33 PM

기사는 PHP 5.3에 도입 된 PHP의 LSB (Late STATIC BING)에 대해 논의하여 정적 방법의 런타임 해상도가보다 유연한 상속을 요구할 수있게한다. LSB의 실제 응용 프로그램 및 잠재적 성능

PHP의 CURL 라이브러리를 사용하여 JSON 데이터가 포함 된 게시물 요청을 보내는 방법은 무엇입니까? PHP의 CURL 라이브러리를 사용하여 JSON 데이터가 포함 된 게시물 요청을 보내는 방법은 무엇입니까? Apr 01, 2025 pm 03:12 PM

PHP 개발에서 PHP의 CURL 라이브러리를 사용하여 JSON 데이터를 보내면 종종 외부 API와 상호 작용해야합니다. 일반적인 방법 중 하나는 컬 라이브러리를 사용하여 게시물을 보내는 것입니다 ...

프레임 워크 보안 기능 : 취약점 보호. 프레임 워크 보안 기능 : 취약점 보호. Mar 28, 2025 pm 05:11 PM

기사는 입력 유효성 검사, 인증 및 정기 업데이트를 포함한 취약점을 방지하기 위해 프레임 워크의 필수 보안 기능을 논의합니다.

프레임 워크 사용자 정의/확장 : 사용자 정의 기능을 추가하는 방법. 프레임 워크 사용자 정의/확장 : 사용자 정의 기능을 추가하는 방법. Mar 28, 2025 pm 05:12 PM

이 기사에서는 프레임 워크에 사용자 정의 기능 추가, 아키텍처 이해, 확장 지점 식별 및 통합 및 디버깅을위한 모범 사례에 중점을 둡니다.

See all articles