Created
April 14, 2016 20:02
-
-
Save dcabanaw/929c0bbf8c5dea56c41f29cba55bccd3 to your computer and use it in GitHub Desktop.
a simple (:effort:) key value store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'Store.php'; | |
// might want to change this so the db file is not in your webroot. Like: | |
// $store = new Store(new PDO('sqlite:' . dirname(__FILE__) . '/../data.db')); | |
$store = new Store(new PDO('sqlite:data.db')); | |
$store->createTable(); | |
if (isset($_GET['key'])) | |
{ | |
$data = $store->get($_GET['key']); | |
if (!empty($data)) | |
{ | |
echo $data['value']; | |
} | |
else | |
{ | |
header('', true, 404); | |
echo '404 - Not Found'; | |
} | |
} | |
else if (isset($_POST['key']) && isset($_POST['value'])) | |
{ | |
$store->put($_POST['key'], $_POST['value']); | |
echo 'OK'; | |
} | |
else | |
{ | |
header('', true, 400); | |
echo '400 - Bad Request'; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Store | |
{ | |
public function __construct(\PDO $db) | |
{ | |
$this->db = $db; | |
$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); | |
} | |
public function createTable() | |
{ | |
$this->db->exec('CREATE TABLE IF NOT EXISTS `data` (`key` TEXT PRIMARY KEY, `value` TEXT);'); | |
} | |
/** | |
* | |
* Create or update an existing key-value pair | |
* | |
* @param $key | |
* @param $value | |
* | |
* @return bool | |
*/ | |
public function put($key, $value) | |
{ | |
$stmt = $this->db->prepare('INSERT OR REPLACE INTO `data` (`key`, `value`) VALUES (?, ?)'); | |
return $stmt->execute([$key, $value]); | |
} | |
/** | |
* | |
* Get an existing key-value pair | |
* | |
* @param $key | |
* | |
* @return array | |
*/ | |
public function get($key) | |
{ | |
$stmt = $this->db->prepare('SELECT * FROM `data` WHERE `key` = ?'); | |
$stmt->execute([$key]); | |
return $stmt->fetch(\PDO::FETCH_ASSOC); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment