Model.php 704 B

1234567891011121314151617181920212223242526272829303132333435
  1. <?php
  2. use Symfony\Component\HttpFoundation\Response;
  3. class Model {
  4. protected $data;
  5. protected $path;
  6. public function __construct(string $path) {
  7. $this->path = $path;
  8. }
  9. public function load() {
  10. $raw = file_get_contents($this->path);
  11. $this->data = json_decode($raw, true);
  12. return $this->data;
  13. }
  14. public function save(array $doc) {
  15. if (empty($doc['id'])) {
  16. $id = (int) max(array_keys($this->data)) + 1;
  17. $doc['id'] = $id;
  18. $created = true;
  19. }
  20. else {
  21. $id = (int) $doc['id'];
  22. $created = false;
  23. }
  24. $this->data[$id] = $doc;
  25. $raw = json_encode($this->data);
  26. file_put_contents($this->path, $raw);
  27. return $created;
  28. }
  29. }