1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- <?php
- use Symfony\Component\HttpFoundation\Response;
- class Model {
- protected $data = [];
- protected $path;
- public function __construct(string $path) {
- $this->path = $path;
- }
- /**
- * Flush the in-memory storage to disk. Do not load it first.
- */
- protected function store() {
- $raw = json_encode($this->data, JSON_PRETTY_PRINT);
- file_put_contents($this->path, $raw);
- }
- public function load() {
- $raw = file_get_contents($this->path);
- $this->data = json_decode($raw, true);
- return $this->data;
- }
- public function save(array $doc) {
- $this->load();
- if (empty($doc['id'])) {
- $id = (int) max(array_keys($this->data)) + 1;
- $doc['id'] = $id;
- $created = true;
- }
- else {
- $id = (int) $doc['id'];
- $created = false;
- }
- $this->data[$id] = $doc;
- $this->store();
- return $created;
- }
- public function delete(int $id) {
- $this->load();
- if (!isset($this->data[$id])) {
- return FALSE;
- }
- unset($this->data[$id]);
- $this->store();
- return TRUE;
- }
- }
|