Model.php 1019 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. class Model {
  3. protected $data = [];
  4. protected $path;
  5. public function __construct(string $path) {
  6. $this->path = $path;
  7. }
  8. /**
  9. * Flush the in-memory storage to disk. Do not load it first.
  10. */
  11. protected function store() {
  12. $raw = json_encode($this->data, JSON_PRETTY_PRINT);
  13. file_put_contents($this->path, $raw);
  14. }
  15. public function load() {
  16. $raw = file_get_contents($this->path);
  17. $this->data = json_decode($raw, true);
  18. return $this->data;
  19. }
  20. public function save(array $doc) {
  21. $this->load();
  22. if (empty($doc['id'])) {
  23. $id = (int) max(array_keys($this->data)) + 1;
  24. $doc['id'] = $id;
  25. $created = true;
  26. }
  27. else {
  28. $id = (int) $doc['id'];
  29. $created = false;
  30. }
  31. $this->data[$id] = $doc;
  32. $this->store();
  33. return $created;
  34. }
  35. public function delete(int $id) {
  36. $this->load();
  37. if (!isset($this->data[$id])) {
  38. return FALSE;
  39. }
  40. unset($this->data[$id]);
  41. $this->store();
  42. return TRUE;
  43. }
  44. }