· 7 years ago · Nov 17, 2018, 04:34 PM
1<?php
2
3//The actual implementation is just this file. Others are usage and tests.
4
5class TodoList extends ArrayObject
6{
7 const CREATE = 'CREATE TABLE IF NOT EXISTS tasks (name VARCHAR(32) PRIMARY KEY, status INT)';
8 const SELECT = 'SELECT * FROM tasks';
9 const INSERT = 'INSERT INTO tasks VALUES (?,?)';
10 const UPDATE = 'UPDATE tasks SET status = ? WHERE name = ?';
11 const DELETE = 'DELETE FROM tasks WHERE name = ?';
12
13 protected $db;
14
15 public function __construct(PDO $db)
16 {
17 $this->db = $db;
18 $db->exec(static::CREATE);
19 $data = $db->query(static::SELECT, PDO::FETCH_KEY_PAIR)->fetchAll();
20 parent::__construct($data, static::ARRAY_AS_PROPS);
21 }
22 public function offsetSet($task, $status)
23 {
24 if (!isset($this[$task]))
25 $this->db->prepare(static::INSERT)->execute(array($task, $status));
26 else
27 $this->db->prepare(static::UPDATE)->execute(array($status, $task));
28 parent::offsetSet($task, $status);
29 }
30 public function offsetUnset($task)
31 {
32 $this->db->prepare(static::DELETE)->execute($task);
33 parent::offsetUnset($task);
34 }
35}