Skip to content

Instantly share code, notes, and snippets.

@alexsandro-xpt
Forked from alganet/todo.php
Created September 28, 2012 03:17
Show Gist options
  • Save alexsandro-xpt/3797758 to your computer and use it in GitHub Desktop.
Save alexsandro-xpt/3797758 to your computer and use it in GitHub Desktop.
A very small PHP todo list that saves to the database in 32 lines
<?php
//The actual implementation is just this file. Others are usage and tests.
class TodoList extends ArrayObject
{
const CREATE = 'CREATE TABLE IF NOT EXISTS tasks (name VARCHAR(32) PRIMARY KEY, status INT)';
const SELECT = 'SELECT * FROM tasks';
const INSERT = 'INSERT INTO tasks VALUES (?,?)';
const UPDATE = 'UPDATE tasks SET status = ? WHERE name = ?';
const DELETE = 'DELETE FROM tasks WHERE name = ?';
protected $db;
public function __construct(PDO $db)
{
$this->db = $db;
$db->exec(static::CREATE);
$data = $db->query(static::SELECT, PDO::FETCH_KEY_PAIR)->fetchAll();
parent::__construct($data, static::ARRAY_AS_PROPS);
}
public function offsetSet($task, $status)
{
if (!isset($this[$task]))
$this->db->prepare(static::INSERT)->execute(array($task, $status));
else
$this->db->prepare(static::UPDATE)->execute(array($status, $task));
parent::offsetSet($task, $status);
}
public function offsetUnset($task)
{
$this->db->prepare(static::DELETE)->execute($task);
parent::offsetUnset($task);
}
}
<?php
$todo = new TodoList(new PDO('mysql:host=localhost;dbName=tasks', 'user', 'pass'));
$todo['Implement the todo list'] = true; //done it!
$todo['Create some tests'] = false; //not done yet
unset($todo['Make a gist']); //remove this one
<?php
//Incomplete! Wanna help?
class TodoListTest extends PHPUnit_Framework_TestCase {
public function setUp($data = array())
{
$this->db = $this->getMock('PDO', array('exec', 'query', 'prepare'), array('sqlite::memory:'));
$this->db->expects($this->once())
->method('exec')
->with($this->equalTo(TodoList::CREATE, PDO::FETCH_KEY_PAIR));
$this->stm = $this->getMock('PDOStatement', array('fetchAll', 'execute'));
$this->stm->expects($this->once())
->method('fetchAll')
->will($this->returnValue($data));
$this->db->expects($this->once())
->method('query')
->with(TodoList::SELECT)
->will($this->returnValue($this->stm));
$this->todo = new TodoList($this->db);
}
public function testConstructor() {
$this->setUp(array('Foo' => true, 'Bar' => false));
$this->assertCount(2, $this->todo);
$this->assertEquals($this->todo['Foo'], true);
$this->assertEquals($this->todo['Bar'], false);
}
public function testOffsetSet() {
$this->stm->expects($this->once())
->method('execute')
->with($this->equalTo(array('Baz', true)));
$this->db->expects($this->once())
->method('prepare')
->with($this->equalTo(TodoList::INSERT))
->will($this->returnValue($this->stm));
$this->todo['Baz'] = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment