mirror of
https://github.com/silverstripe/silverstripe-framework
synced 2024-10-22 14:05:37 +02:00
#1730 - Caching in RestfulService (merged from branches/2.2.0, r44881)
git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@44915 467b73ca-7a2a-4603-9d3b-597d59a354a9
This commit is contained in:
parent
b5098645fc
commit
85d6566e32
@ -9,9 +9,12 @@ class RestfulService extends ViewableData {
|
||||
protected $queryString;
|
||||
protected $rawXML;
|
||||
protected $errorTag;
|
||||
protected $checkErrors;
|
||||
protected $cache_expire;
|
||||
|
||||
function __construct($base){
|
||||
function __construct($base, $expiry=3600){
|
||||
$this->baseURL = $base;
|
||||
$this->cache_expire = $expiry;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -32,8 +35,19 @@ class RestfulService extends ViewableData {
|
||||
*/
|
||||
|
||||
function connect(){
|
||||
$url = $this->constructURL();
|
||||
$url = $this->constructURL(); // url for the request
|
||||
|
||||
// check for file exists in cache
|
||||
// set the cache directory
|
||||
$cachedir = TEMP_FOLDER; // default silverstripe-cache
|
||||
|
||||
$cache_file = md5($url); // encoded name of cache file
|
||||
$cache_path = $cachedir . "/$cache_file";
|
||||
|
||||
if((@file_exists("$cache_path") && ((@filemtime($cache_path) + $this->cache_expire) > (time())))){
|
||||
$this->rawXML = file_get_contents($cache_path);
|
||||
} else {
|
||||
// not available in cache fetch from server
|
||||
$ch = curl_init();
|
||||
$timeout = 5;
|
||||
curl_setopt($ch, CURLOPT_URL, $url);
|
||||
@ -42,18 +56,26 @@ class RestfulService extends ViewableData {
|
||||
$this->rawXML = curl_exec($ch);
|
||||
curl_close($ch);
|
||||
|
||||
//Debug::show($url);
|
||||
// save the response in cache
|
||||
$fp = @fopen($cache_path,"w+");
|
||||
@fwrite($fp,$this->rawXML);
|
||||
@fclose($fp);
|
||||
}
|
||||
|
||||
//Try using file_get_contents if cURL is not installed in your system.
|
||||
//$this->rawXML = file_get_contents($url);
|
||||
if($this->rawXML != "")
|
||||
if($this->checkErrors == true)
|
||||
// Try using file_get_contents if cURL is not installed in your system.
|
||||
// $this->rawXML = file_get_contents($url);
|
||||
|
||||
// results returned - from cache / live
|
||||
if($this->rawXML != ""){
|
||||
if($this->checkErrors == true) {
|
||||
return $this->errorCatch($this->rawXML);
|
||||
else
|
||||
} else {
|
||||
return $this->rawXML;
|
||||
else
|
||||
}
|
||||
} else {
|
||||
user_error("Invalid Response (maybe your calling to wrong URL or server unavailable)", E_USER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets attributes as an array, of a particular type of element.
|
||||
|
Loading…
Reference in New Issue
Block a user