mongo.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. /*
  3. Copyright (c) 2009-2014 F3::Factory/Bong Cosca, All rights reserved.
  4. This file is part of the Fat-Free Framework (http://fatfree.sf.net).
  5. THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF
  6. ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  7. IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
  8. PURPOSE.
  9. Please see the license.txt file for more information.
  10. */
  11. namespace DB;
  12. //! MongoDB wrapper
  13. class Mongo {
  14. //@{
  15. const
  16. E_Profiler='MongoDB profiler is disabled';
  17. //@}
  18. protected
  19. //! UUID
  20. $uuid,
  21. //! Data source name
  22. $dsn,
  23. //! MongoDB object
  24. $db,
  25. //! MongoDB log
  26. $log;
  27. /**
  28. * Return data source name
  29. * @return string
  30. **/
  31. function dsn() {
  32. return $this->dsn;
  33. }
  34. /**
  35. * Return UUID
  36. * @return string
  37. **/
  38. function uuid() {
  39. return $this->uuid;
  40. }
  41. /**
  42. * Return MongoDB profiler results
  43. * @return string
  44. **/
  45. function log() {
  46. $cursor=$this->selectcollection('system.profile')->find();
  47. foreach (iterator_to_array($cursor) as $frame)
  48. if (!preg_match('/\.system\..+$/',$frame['ns']))
  49. $this->log.=date('r',$frame['ts']->sec).' ('.
  50. sprintf('%.1f',$frame['millis']).'ms) '.
  51. $frame['ns'].' ['.$frame['op'].'] '.
  52. (empty($frame['query'])?
  53. '':json_encode($frame['query'])).
  54. (empty($frame['command'])?
  55. '':json_encode($frame['command'])).
  56. PHP_EOL;
  57. return $this->log;
  58. }
  59. /**
  60. * Intercept native call to re-enable profiler
  61. * @return int
  62. **/
  63. function drop() {
  64. $out=$this->db->drop();
  65. $this->setprofilinglevel(2);
  66. return $out;
  67. }
  68. /**
  69. * Redirect call to MongoDB object
  70. * @return mixed
  71. * @param $func string
  72. * @param $args array
  73. **/
  74. function __call($func,array $args) {
  75. return call_user_func_array(array($this->db,$func),$args);
  76. }
  77. /**
  78. * Instantiate class
  79. * @param $dsn string
  80. * @param $dbname string
  81. * @param $options array
  82. **/
  83. function __construct($dsn,$dbname,array $options=NULL) {
  84. $this->uuid=\Base::instance()->hash($this->dsn=$dsn);
  85. $class=class_exists('\MongoClient')?'\MongoClient':'\Mongo';
  86. $this->db=new \MongoDB(new $class($dsn,$options?:array()),$dbname);
  87. $this->setprofilinglevel(2);
  88. }
  89. }