Skip to content

Instantly share code, notes, and snippets.

@johnvilsack
Created December 15, 2014 17:10
Show Gist options
  • Save johnvilsack/cfe7a36c0582d4ebf8cc to your computer and use it in GitHub Desktop.
Save johnvilsack/cfe7a36c0582d4ebf8cc to your computer and use it in GitHub Desktop.
Simple PDO to File Cache for PHP
<?php
// This is a simple way to cache queries to your local filesystem while maintaining control over their freshness.
// Great for those nasty archival queries that data changes don't happen to.
// Free to all, forever - John Vilsack 2014
$file = './cache/**FILENAME**.cache'; // Path and name of .cache file
$expire = 900; // # of seconds before cache is stale
// Function to create the cached file.
function makeCache($file) {
// Create PDO connection
$pdo = new PDO('mysql:host=**HOST**;port=**PORT**;dbname=**DATABASE**', '**DBUSER**', '**DBPASSWORD**');
// Do your thing
$query = $pdo->prepare('**SQLSTATEMENT**');
$query->execute();
$result = $query->fetchAll();
unset($query);
// OPTIONAL: Encode array in JSON
$result = json_encode($result);
// Put data in file.
$fp = fopen($file,"w");
fputs($fp,$result);
fclose($fp);
// You need whatever you just cached, so return it.
return $result;
}
// Function to check cache and retrieve its bits.
function checkCache($file) {
// Check file create time vs. your expire.
if (filemtime($file) < (time() - $expire)) {
$result = makeCache($file);
} else {
// It's cached and it's current, so retrieve it.
$result = file_get_contents($file);
}
return $result;
}
// Your new, tidy way of retrieving data while setting a cache.
$data = file_exists($file) ? checkCache($file) : makeCache($file);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment