Search code examples
phpmysqljsonapachelamp

How to design a simple page cache?


I would like to limit the number of times a page is generated in a certain time frame, but am unsure of how to even approach the problem.

Previously, I have solved similar problems by scheduling the pages to be generated and saved in a cron job, but this will not allow me to do this dynamically.

Here is the scenario:

I have n number of user created rooms. I would like to build a JSON api to allow the users to access room information for use on their own pages. However, generating a new JSON result for every request would be extremely inefficient and impose security risks on the database server. I would like to limit it, so that all requests in x amount of time use the same JSON result rather than new results each time.


Solution

  • a simple caching system can be done like this

     if (!file_exists($cacheFile) || filemtime($cacheFile) - time() > $cacheLifetime){
         //generate json and save to $cacheFile
     }
     header("Content-Type: application/json");
     header("Content-Length: ".filesize($cacheFile));
     readfile($cacheFile);