Reputation: 21
I want to cache the API responses so that number of requests to the API server are reduced. API's are written in PHP using zend framework. My approach: I created a redis cluster and I used phpfastcache to connect to redis cluster. Using phpfastcache, we can only set the expiry time for the cached response. Whenever the response is updated before expiry of cache, we get the older response with the approach mentioned above. Desired thing is that whenever response is updated, old cache must be cleared and new cache must be written with same key. I have attached a sample script that I used. It would be great if anyone can provide me solution for this. Thanks in advance. Code:
<?php
// phpfastcache is a package used for caching
use Phpfastcache\CacheManager;
use Phpfastcache\Drivers\Redis\Config;
require //path for composer autoloader;
#InstanceCache must be global
$InstanceCache = CacheManager::getInstance('redis', new Config([
'host' => 'IP_address',
'port' => 6379,
'password' => //password
'database' => //db_name
]));
public function function_name(parameter){
$key = "unique_name";
$CacheString = $InstanceCache->getItem($key);
if(is_null($CacheString->get())){
$sql="SELECT * FROM employees";//sql query for function_name
$res=$this->db_query($sql);
if($this->db_num_rows($res)==0):
$this->db_free_results($res);
else:
$row = $this->db_fetch_object($res);
$this->db_free_results($res);
endif;
$CacheString->set($row)->expiresAfter(/*time*/);
$InstanceCache->save($CacheString);
echo $CacheString->get();
}
else{
echo $CacheString->get();
}
}
?>
Upvotes: 1
Views: 2315
Reputation: 454
Like I told you on Github, I think you misunderstood the concept itself of caching. The concept caching means that you cache your data for a desired TTL.
If you need the most fresh data then you must re-fetch from source (your database here ).
Cache is not means to be dynamic, it's means to be static and to help you cool down the request on your backend.
So in your case, just fetch from source without caching and it'll be good. It does not make any sense to ask Phpfastcache interrogate your database each time then compare the data to the cached data to check if your database data are fresher.
In fact the cost in time of the whole operation will be longer than only fetching from the source.
Upvotes: 1