Caching API responses with PHP
Most websites have some kind of widget that fetches data from an external RESTful API provided by services such as Twitter, Flickr and Facebook to name just a few. These APIs often limit the amount of hits any one Domain/IP can make and if you go over your rate limit then pow, no data for you and an empty widget. This PHP class gives you a mechanism to cache your API responses locally and only update them on a set time interval so you always stay within the rate limits for each API call you make from your site.
The class accepts a URI for your API call, a filename to write to (if this is not in the same directory as the class you will need to make sure that directory exists), and a time period for how long you wish to cache the response for. Each time the cache contents are requested the object checks to see if the file is out of date before updating it and returning the files contents. Of course if the file is up to date it just return its contents and does not make the API call. This avoids going over the API rate limit and also reduces unnecessary network traffic giving a better experience for your visitors in general. Below is the code for the API_cache class.
Using the API_cache class effectively
Here is an example usage of the class taken from the demo. The flexibility of this class means you could have cached your API response in any format, it doesn’t need to be JSON this is just my preferred option as I generally use Ajax to build the widgets once the site content has loaded. All you need to do is build up your API URI, tell it which file to write to and set how often you want to update it – instantiate your cache object and ask it for your API response. You could even use it to cache other external data such as atom feeds pulled in from other sites.
The class also has a getter for the cache expiry date and time–returned in HTTP header format–that you can use to build up your response headers and let the client know how long to cache the response for.
No related posts.