Reputation: 2699
for a web application (an Image Database) I am using the Restful Server Module. The Data is requested by another web application (a shop). The generation of the XML takes up to 1 second. the shop has to wait for the API to answer to display for example a Product Page. Is it possible to activate some caching for the Restful Server API?
I tried already with the Static Publisher but it seems to work just with cms pages. Many thanks, Florian
Upvotes: 0
Views: 631
Reputation: 1809
RestfulService does the caching for you. It accepts 2 paramaters. A serviceURL and also a cache time. The default is 3600 (1 hour). This is only going to work if the shop is built with silverstripe.
$serviceURL = 'http://www.imagedatabase.com/api/v1/Product?ID=1';
$service = new RestfulService($serviceURL, 7200); //2 hours expiry
$xml = $service->request()->getBody();
//get fields values
$productName = $service->searchValue($xml, 'Name');
$productPrice = $service->searchValue($xml, 'Price');
You also need to make a modification to Product assuming Product is a dataobject.
class Product extends DataObject {
...
static $api_access = true;
...
function canView($member = null) {
return true;
}
}
RestfulService docs http://doc.silverstripe.org/framework/en/reference/restfulservice
Upvotes: 2
Reputation: 4015
well, I personally would cache on the client (so in the shop)
but if you have to, I don't think there is any built in way for this. you could subclass the restful server and do some basic caching yourself (just the way the default SS RestfulClient does it, save it into a file)
class MyServer extends RestfulServer {
public $cache_expire;
function __construct($cache_expire = 3600) {
$this->cache_expire = $cache_expire;
}
protected function getHandler($className, $id, $relationName) {
$cache_path = Director::getAbsFile("assets/rest-cache/$className-$id-$relationName.{$this->request->getExtension()}");
if ($this->cache_expire > 0 && !isset($_GET['flush'])
&& @file_exists($cache_path) && @filemtime($cache_path) + $this->cache_expire > time()
) {
$store = file_get_contents($cache_path);
$response = unserialize($store);
} else {
$response = parent::getHandler($className, $id, $relationName);
$store = serialize($response);
file_put_contents($cache_path, $store);
}
return $response;
}
}
// NOTE, I have never tested this code, so you might run into minor spelling mistakes or something like that
Upvotes: 1