A cache must always have a limit, both for resource usage and for performance. As already discussed, many systems use time-based on-demand caching. This means the system remains alert and periodically collects expired cache entries at a predefined interval. This is one of the most widely used approaches.
Instead, I propose limiting the number of stored resources rather than their storage time.
$cacheFile = $this->folder.$this->request;
$dir = opendir($this->folder);
//If the maximum file count is reached, delete the oldest file
if($this->countFiles() >= $this->limit){
if($this->deleteOldest())
if(file_put_contents($this->folder.$this->request, $buffer));
return true;
}
else{
if(file_put_contents($this->folder.$this->request, $buffer));
return true;
}
With a fixed limit, the next request for an uncached resource stores it in the cache and removes the oldest stored resource to stay within the limit.
The system will thus keep the resources most in demand at that moment in its cache.
Unlike time-based systems, which must monitor content expiry and consume resources doing so, this cache renews itself automatically within the established limits.
To prevent caching from compromising information integrity during content updates, generic back-end methods should clear the cache whenever content is modified, deleted or added. This part is not implemented, but it is the intended design.
One possible implementation would use a database stored procedure, triggered by any INSERT, UPDATE or DELETE operation that changes content, to set a field to true. Each time the application runs, it would check this value to decide whether to use the existing cache or discard it as obsolete.
Another possibility would be a manually invoked back-end method that clears the cache after every CRUD operation in the models.
This would ensure that the end user never sees outdated content.
