Local.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. <?php
  2. namespace app\framework\Repository\Source;
  3. use app\common\models\BaseModel;
  4. use app\framework\Repository\RepositorySourceInterface;
  5. class Local implements RepositorySourceInterface
  6. {
  7. /**
  8. * @var array
  9. */
  10. private $all;
  11. private $items;
  12. private $model;
  13. public function __construct(BaseModel $model)
  14. {
  15. $this->model = $model;
  16. }
  17. public function find($id)
  18. {
  19. return $this->items[$id];
  20. }
  21. /**
  22. * 按字段查找
  23. * @param $key
  24. * @param $ids
  25. * @return array
  26. */
  27. public function findManyBy($key, $ids)
  28. {
  29. $result = null;
  30. foreach ($this->items as $id => $item) {
  31. if (in_array($item[$key], $ids)) {
  32. $id = $item[$this->model->getKeyName()];
  33. $result[$id] = $item[$key];
  34. }
  35. if (count($result) == count($ids)) {
  36. //全部找到时终止
  37. break;
  38. }
  39. }
  40. return $result;
  41. }
  42. public function findBy($key, $id)
  43. {
  44. foreach ($this->items as $item) {
  45. if ($item[$key] == $id) {
  46. return $item;
  47. }
  48. }
  49. return null;
  50. }
  51. /**
  52. * 按id查找
  53. * @param $key
  54. * @param $ids
  55. * @return array
  56. */
  57. public function findMany($ids)
  58. {
  59. $result = null;
  60. foreach ($this->items as $id => $item) {
  61. if (in_array($id, $ids)) {
  62. $result[$id] = $item;
  63. }
  64. if (count($result) == count($ids)) {
  65. //全部找到时终止
  66. break;
  67. }
  68. }
  69. return $result;
  70. }
  71. public function all()
  72. {
  73. return $this->all;
  74. }
  75. public function save($id, $data)
  76. {
  77. $this->items[$id] = $data;
  78. return true;
  79. }
  80. public function saveMany($data)
  81. {
  82. $this->items = array_merge($this->items, $data);
  83. }
  84. public function saveBy($key, $id, $data)
  85. {
  86. $this->items[$this->model->getKeyName()] = $data;
  87. }
  88. public function saveManyBy($key, $data)
  89. {
  90. foreach ($data as $item) {
  91. $this->saveBy($key, $item[$key], $item);
  92. }
  93. }
  94. public function saveAll($data)
  95. {
  96. $this->all = $data;
  97. return true;
  98. }
  99. public function flush()
  100. {
  101. unset($this->items);
  102. unset($this->all);
  103. return true;
  104. }
  105. }