improve cache invalidation for curl

This commit is contained in:
Jeremy Kauffman 2016-10-13 17:05:27 -04:00
parent 0d5fd01e8f
commit c6cf3f2a89

View file

@ -6,13 +6,15 @@ class CurlWithCache extends Curl
public static function doCurl($method, $url, $params = [], $options = []) public static function doCurl($method, $url, $params = [], $options = [])
{ {
$useCache = ($options['cache'] ?? true) && Apc::isEnabled(); $cacheAllowed = $options['cache'] ?? true;
$cacheEnabled = Apc::isEnabled();
$cacheTimeout = is_numeric($options['cache'] ?? null) ? $options['cache'] : static::DEFAULT_CACHE; $cacheTimeout = is_numeric($options['cache'] ?? null) ? $options['cache'] : static::DEFAULT_CACHE;
unset($options['cache']); unset($options['cache']);
if ($useCache) $cacheKey = $cacheEnabled ? md5($url . $method . serialize($options) . serialize($params)) : null;
if ($cacheAllowed && $cacheKey)
{ {
$cacheKey = md5('x' . $url . $method . serialize($options) . serialize($params));
$cachedData = apc_fetch($cacheKey); $cachedData = apc_fetch($cacheKey);
if ($cachedData) if ($cachedData)
{ {
@ -22,10 +24,17 @@ class CurlWithCache extends Curl
$response = parent::doCurl($method, $url, $params, $options); $response = parent::doCurl($method, $url, $params, $options);
if ($useCache) if ($cacheEnabled)
{
if ($cacheAllowed)
{ {
apc_store($cacheKey, $response, $cacheTimeout); apc_store($cacheKey, $response, $cacheTimeout);
} }
else
{
apc_delete($cacheKey);
}
}
return $response; return $response;
} }