You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.4 KiB

  1. <?php
  2. /**
  3. * Класс модели данных
  4. *
  5. * @copyright NetMonsters <team@netmonsters.ru>
  6. * @link http://netmonsters.ru
  7. * @package Majestic
  8. * @subpackage Model
  9. * @since 2011-11-15
  10. */
  11. abstract class MongoModel extends Model
  12. {
  13. protected $useMongoId = true;
  14. public function __construct($connection = 'default')
  15. {
  16. parent::__construct($connection);
  17. }
  18. public function count($query = array(), $limit = 0, $skip = 0)
  19. {
  20. return $this->db->count($this->table(), $query, $limit, $skip);
  21. }
  22. public function find($condition = array(), $fields = array())
  23. {
  24. return $this->db->find($this->table(), $condition, $fields);
  25. }
  26. public function get($id)
  27. {
  28. if ($this->useMongoId) {
  29. if (!$id instanceof MongoId) {
  30. $id = new MongoId($id);
  31. }
  32. }
  33. return $this->db->get($this->table(), array('_id' => $id))->fetch();
  34. }
  35. public function batchInsert($data)
  36. {
  37. return $this->db->insert($this->table(), $data, true);
  38. }
  39. public function delete($id)
  40. {
  41. if ($this->useMongoId) {
  42. if (!$id instanceof MongoId) {
  43. $id = new MongoId($id);
  44. }
  45. }
  46. return $this->db->delete($this->table(), array('_id' => $id));
  47. }
  48. public function deleteAll($query = array())
  49. {
  50. $this->db->delete($this->table(), $query);
  51. }
  52. protected function fetchField($data, $params = array(), $field, $cache_key = null)
  53. {
  54. if (!$cache_key || !$result = $cache_key->get()) {
  55. $result = $this->db->find($this->table(), $data, array($field => 1))->fetchField($field);
  56. if ($cache_key) {
  57. $cache_key->set($result);
  58. }
  59. }
  60. return $result;
  61. }
  62. protected function fetch($data, $params = array(), $cache_key = null)
  63. {
  64. if (!$cache_key || !$result = $cache_key->get()) {
  65. $result = $this->db->find($this->table(), $data)->fetch();
  66. if ($cache_key) {
  67. $cache_key->set($result);
  68. }
  69. }
  70. return $result;
  71. }
  72. protected function fetchAll($data, $params = array(), $cache_key = null)
  73. {
  74. if (!$cache_key || !$result = $cache_key->get()) {
  75. $result = $this->db->find($this->table(), $data)->fetchAll();
  76. if ($cache_key) {
  77. $cache_key->set($result);
  78. }
  79. }
  80. return $result;
  81. }
  82. }