We recommend operating a cache for your implementation. Caching is not required and the feeds will support live queries. However, it is good practice to use one. Not only does it reduce unnecessary network trips but will also increase the responsiveness of your application.
Of course, caching can be implemented in a number of ways and a “cache” can have a number of different definitions. If your implementation pulls all content before the a page is generated (e.g. a “data dump”) then a form of cache has already been implemented. That’s not to say that additional forms of cache need not be applied when that content reaches the page. If however, the implementation uses dynamic retrieval then feeds can be cached the 1st time they are called dynamically. To understand more about the differences between “Data Dump” and “Dynamic” retrieval patterns then read our Getting Started section on Deciding Retrieval Approach.
Caching Strategies
Calculating the correct caching strategy can be quite complex and is largely dependent on your implementation. Technically, the feed content can update itself at any time. We have teams working across the world updating content so there isn’t a set of useful “office hours”. Discrete items like Events or POIs update throughout the day but larger things like Guides (which can contain Events or POIs) are done in batches. You will be advised by your account manager what content update schedule to expect depending on what content has been licensed. A good rule of thumb is that no content needs to live any longer than 24hrs in a cache.
You should structure your cache depending on the size of your site, the data it holds and the type of traffic it can expect. Obviously, it’s a good idea to cache requests that are hit more often than not. There’s no point wasting memory by caching a feed request only one user has asked for. However, it might just be easier to throw every request into a cache because the content set is not that large, or memory is not an issue.
Implementing a dynamic PHP cache
Implementing a cache when collecting feeds dynamically upon request is quite straightforward.
Using APC Cache, a PHP extension, you can push and pull XML from a memory cache. This can ensure that the feed data is only requested once across the application and stored for the configured amount of time.
function getFeedContents($url, $ttl = 15) {
// Generate a cache key for the url
$key = md5($url);
// Query the cache, if empty then call the feed
if(!($xml = cache_get($key))) {
// Retrieve feed url using curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$xml = curl_exec($ch);
curl_close($ch);
// Store the response in the cache
apc_store($key, $xml, $ttl);
}
return new SimpleXMLElement($xml);
}