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.

89 lines
2.3 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 delete($id)
  36. {
  37. if($this->useMongoId) {
  38. if(! $id instanceof MongoId) {
  39. $id = new MongoId($id);
  40. }
  41. }
  42. return $this->db->delete($this->table(), array('_id' => $id));
  43. }
  44. public function deleteAll($query = array())
  45. {
  46. $this->db->delete($this->table(), $query);
  47. }
  48. protected function fetchField($data, $params = array(), $field, $cache_key = null)
  49. {
  50. if (!$cache_key || !$result = $cache_key->get()) {
  51. $result = $this->db->find($this->table(), $data, array($field => 1))->fetchField($field);
  52. if ($cache_key) {
  53. $cache_key->set($result);
  54. }
  55. }
  56. return $result;
  57. }
  58. protected function fetch($data, $params = array(), $cache_key = null)
  59. {
  60. if (!$cache_key || !$result = $cache_key->get()) {
  61. $result = $this->db->find($this->table(), $data)->fetch();
  62. if ($cache_key) {
  63. $cache_key->set($result);
  64. }
  65. }
  66. return $result;
  67. }
  68. protected function fetchAll($data, $params = array(), $cache_key = null)
  69. {
  70. if (!$cache_key || !$result = $cache_key->get()) {
  71. $result = $this->db->find($this->table(), $data)->fetchAll();
  72. if ($cache_key) {
  73. $cache_key->set($result);
  74. }
  75. }
  76. return $result;
  77. }
  78. }