Skip to content

Instantly share code, notes, and snippets.

@bmcminn
Created September 4, 2019 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmcminn/cfaa30fa654c88ee67dfea1f07ee913b to your computer and use it in GitHub Desktop.
Save bmcminn/cfaa30fa654c88ee67dfea1f07ee913b to your computer and use it in GitHub Desktop.
initial attempt at a memoization mechanism
<?php
/**
* Memoizes a given set of data and returns if a result has been cached or not
* @param array $params Config for what to memoize
* @param (any) $data (optional) Data we wish to memoize
* @return any [description]
*/
function memoize($key, $data=null) {
$db = null;
$dbType = 'sqlite';
$dbPath = './test.db';
$tableName = 'memos';
$cacheTime = microtime(true);
$cacheTimeLimit = 5; // in minutes
$cacheBust = ($cacheTime + (1000 * 60 * 60 * $cacheTimeLimit));
$res = 'pants';
// TODO: write this whole thing in SQLite?
$sql =
<<<SQL
CREATE TABLE IF NOT EXISTS memos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT NOT NULL UNIQUE,
data TEXT NOT NULL,
cache INTEGER NOT NULL
);
CREATE TEMP TABLE IF NOT EXISTS Variables (
name TEXT PRIMARY KEY,
value TEXT
);
-- https://stackoverflow.com/questions/7739444/declare-variable-in-sqlite-and-use-it
-- Check key exists in DB
SELECT
data
FROM
$tableName
WHERE
key = :keyname
;
SQL>>>;
// Attempt to initialize database connection
try {
$db = new PDO("{$dbType}:{$dbPath}");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// IF table doesn't exist, create it
$db->exec("
CREATE TABLE IF NOT EXISTS {$tableName} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT NOT NULL UNIQUE,
data TEXT NOT NULL,
cache INTEGER NOT NULL
)
");
} catch(PDOException $e) {
print_r($e->getMessage());
return;
}
// IF provided data, write it to the database
if ($data) {
$data = json_encode($data);
try {
$sql = "
UPDATE {$tableName}
SET
key = :keyname,
data = :data,
cache = :cache
WHERE
key = :keyname
";
$stmt = $db->prepare($sql);
$stmt->execute([
':keyname' => $key
, ':data' => $data
, ':cache' => $cacheTime
]);
// $res = $stmt->fetch(\PDO::FETCH_ASSOC);
} catch(PDOException $e) {
print_r($e->getMessage());
return;
}
}
// Return the data from the record in question
try {
$sql = "
SELECT
data
FROM
$tableName
WHERE
key = :keyname
";
$stmt = $db->prepare($sql);
$stmt->execute([
':keyname' => $key
]);
$res = $stmt->fetch(\PDO::FETCH_ASSOC);
} catch(PDOException $e) {
print_r($e->getMessage());
return;
}
// print_r($key);
// print_r($data);
// print_r($res);
return $res[0];
}
echo memoize('free_thinkers_are_dangerous_sd');
echo PHP_EOL;
echo memoize('free_thinkers_are_dangerous_sd');
echo PHP_EOL;
echo memoize('free_thinkers_are_dangerous', ['keyName' => 'value']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment