Created
August 11, 2014 09:33
-
-
Save Mygod/f4143a78e0b10ab9ac3a to your computer and use it in GitHub Desktop.
PHP + PostgreSQL Lightweighted Caching
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
<? | |
$connection_string = '*insert connection string here*'; | |
$cache_id = 123; | |
$expiration_seconds = 86400; | |
function generate_a_huge_string() { | |
sleep(5); | |
return 'An awesome string has been generated!'; | |
} | |
date_default_timezone_set('UTC'); | |
$pg = pg_pconnect($connection_string) or die('Unable to connect to PostgreSQL!'); | |
pg_query($pg, <<<'Query' | |
CREATE TABLE IF NOT EXISTS Cache ( | |
id BIGINT NOT NULL PRIMARY KEY, | |
data TEXT NOT NULL, | |
time TIMESTAMP NOT NULL default (now() at time zone 'utc') | |
); | |
CREATE OR REPLACE FUNCTION upsertCache(a BIGINT, b TEXT) RETURNS VOID AS | |
$$ | |
BEGIN | |
LOOP | |
UPDATE Cache SET data = b, time = now() at time zone 'utc' WHERE id = a; | |
IF found THEN | |
RETURN; | |
END IF; | |
BEGIN | |
INSERT INTO Cache (id, data) VALUES (a, b); | |
RETURN; | |
EXCEPTION WHEN unique_violation THEN | |
END; | |
END LOOP; | |
END; | |
$$ | |
LANGUAGE plpgsql; | |
Query | |
) or die('Initialization failed.'); | |
// show-cache.php | |
$query = pg_query($pg, "SELECT data, time FROM Cache WHERE id = $cache_id") | |
or die('Unable to query data in the database.'); | |
echo ($entry = pg_fetch_array($query)) ? $entry['data'] | |
: '<div class="center">Cache unavailable, please retry later.</div>'; | |
if (!$entry || time() - strtotime($entry['time']) > $expiration_seconds) | |
echo '<script src="refresh-cache.php" async></script>'; | |
// refresh-cache.php | |
pg_query($pg, "SELECT upsertCache($cache_id, '" . pg_escape_string($pg, generate_a_huge_string()) . "');") | |
or die('Unable to update data in the database.'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment