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();
}
}
?>