Started looking at the code. It looks like you check if the value is not a string or int and serialize it. I dont think there is any reason to do this now. We should just serialize everything along with the time. That would also get rid of the is_serialized function since we already know.
But in order to be backwords compatible we would have to leave it in. You could just invalidate it if its not in the right format and publish a note on the update. The cache would be rebuilt next page load for those who update, but small price to pay for the ability to set TTL on file based caching. It would be much cleaner code without backwards compatibility and not rely upon the filesystem which should make it a little faster.
Ive tested both versions, but my vote would be for the first.
Heres my code for the new cache:
/**
* Adds or updates value to the cache
* @param string $key The key that will be associated with the item.
* @param mixed $value The variable to store.
* @param int $ttl Time To Live
* @return bool Returns TRUE on success or FALSE on failure.
*/
protected function set_value($key, $value, $ttl = null)
{
$value = serialize(array('lsdata'=>$value, 'lscache'=>time(), 'lsttl'=>(int)$ttl));
...
}
protected function get_cache_value($key)
{
$dest_path = $this->dir_path.'/'.$key;
if (!file_exists($dest_path))
return false;
$contents = file_get_contents($dest_path);
if (($unserialized = @unserialize($contents)) === false)
return false;
if( !isset($unserialized['lsdata']) )
return false;
if ($unserialized['lsttl'] && ((time() - $unserialized['lscache']) > $unserialized['lsttl']))
{
@unlink($dest_path);
return false;
}
else if ($this->ttl && ((time() - $unserialized['lscache']) > $this->ttl))
{
@unlink($dest_path);
return false;
}
return $unserialized['lsdata'];
}
Heres the backwards compatibility version: (It doesnt check for TTL yet if the object is not serialized).
/**
* Adds or updates value to the cache
* @param string $key The key that will be associated with the item.
* @param mixed $value The variable to store.
* @param int $ttl Time To Live
* @return bool Returns TRUE on success or FALSE on failure.
*/
protected function set_value($key, $value, $ttl = null)
{
$value = serialize(array('lsdata'=>$value, 'lscache'=>time(), 'lsttl'=>(int)$ttl));
...
}
protected function get_cache_value($key)
{
$dest_path = $this->dir_path.'/'.$key;
if (!file_exists($dest_path))
return false;
$contents = file_get_contents($dest_path);
$unserialized = null;
if ( !$this->is_serialized($contents, $unserialized) )
return $contents;
if( is_array($unserialized) && isset($unserialized['lsdata']) )
{
if ($unserialized['lsttl'] && ((time() - $unserialized['lscache']) > $unserialized['lsttl']))
{
@unlink($dest_path);
return false;
}
return $unserialized['lsdata'];
}
else
{
if ($this->ttl && ((time() - filemtime($dest_path)) > $this->ttl))
{
@unlink($dest_path);
return false;
}
return $unserialized;
}
return $contents;
}