Caching JSON output in PHP

前端 未结 2 1107
有刺的猬
有刺的猬 2020-12-04 17:03

Got a slight bit of an issue. Been playing with the facebook and twitter API\'s and getting the JSON output of status search queries no problem, however I\'ve read up furthe

2条回答
  •  眼角桃花
    2020-12-04 17:35

    It's a good idea to use caching to avoid the rate limit. Here's some example code that shows how I did it for Google+ data, in some php code I wrote recently.

    private function getCache($key) {
        $cache_life = intval($this->instance['cache_life']); // minutes
        if ($cache_life <= 0) return null;
    
        // fully-qualified filename
        $fqfname = $this->getCacheFileName($key);
    
        if (file_exists($fqfname)) {
            if (filemtime($fqfname) > (time() - 60 * $cache_life)) {
                // The cache file is fresh.
                $fresh = file_get_contents($fqfname);
                $results = json_decode($fresh,true);
                return $results;
            }
            else {
                unlink($fqfname);
            }
        }
    
        return null;
    }
    
    private function putCache($key, $results) {
        $json = json_encode($results);
        $fqfname = $this->getCacheFileName($key);
        file_put_contents($fqfname, $json, LOCK_EX);
    }
    

    and to use it:

            // $cacheKey is a value that is unique to the
            // concatenation of all params. A string concatenation
            // might work. 
            $results = $this->getCache($cacheKey);
            if (!$results) {
                // cache miss; must call out
                $results = $this->getDataFromService(....);
                $this->putCache($cacheKey, $results);
            }
    

提交回复
热议问题