Is there a built-in way to cache data in plugins? I’m essentially looking for a way to do something like this:
get_url("http://www.some-site.com/api/some-webservice.xml");
function get_url($url) {
$key = md5($url);
if($EXP->cache_exists($key)) {
return $EXP->cache_fetch($key);
}
else {
$data = fetch_url($url); //a method I already have using cURL
return $EXP->cache_store($key, $data);
}
}
Where EE effectively handles the caching behind-the-scenes, or do I need to create something on my own, and if so, how would I use EE to generate the path to the /system/cache/ directory? Hopefully I explained this idea well enough.
Thanks for the input! I’ll be sure to take a look at how magpie goes about handling its caches.
Victor,
Thanks for pointing out how to reference the cache directory, for those interested, here’s the code I came up with so far:
// Get the cached version of the url, if exists and fresh,
// Otherwise fetch it & cache it.
function get_cache($url) {
$cache_dir = PATH_CACHE . 'lastfm_cache/';
$key = md5($url);
if(!file_exists($cache_dir) || !is_dir($cache_dir)) {
mkdir($cache_dir, 0777);
}
$data = "";
$cache_file = $cache_dir . $key;
if(file_exists($cache_file) &&
filemtime($cache_file) >= time() - ($this->cache_time * 60)) {
$handle = fopen($cache_file, 'r');
$data = fread($handle, filesize($cache_file));
fclose($handle);
}
else {
$data = $this->fetch_url($url);
$handle = fopen($cache_file, 'w');
fwrite($handle, $data);
fclose($handle);
}
return $data;
}
function fetch_url($url) {
$ch = curl_init(); // initialize a cURL session
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$str = curl_exec ($ch);
curl_close ($ch);
return (!is_string($str) || !strlen($str)) ? null : $str;
}
I might refine this code more once I get deeper into this plugin, only time will tell.
Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.