Search code examples
phpvimeo

Implement caching for new Vimeo PHP API


I have a project that was written with vimeo-php-lib which has been deprecated, so I have changed it to the new php library. Which can be found at https://github.com/vimeo/vimeo.php

However, the old code has had caching enabled using the line below:

$api->enableCache(phpVimeo::CACHE_FILE, realpath(dirname(APPLICATION_PATH) . DIRECTORY_SEPARATOR .'data' .DIRECTORY_SEPARATOR. 'cache' .DIRECTORY_SEPARATOR. 'vimeo'), 3600);

How do I go about implementing it for the new API? It doesn't seem to be included in the examples.


Solution

  • I edited the current Vimeo.php library so that it will cache the results, it currently expires every 24 hours.

    The _request function was modified, and two more functions were added.

    const CACHE_FILE = 'file';
    private $_cache_enabled = 'file';
    private $_cache_dir = '';
    
    /**
     * Internal function to handle requests, both authenticated and by the upload function.
     *
     * @param string $url
     * @param array $curl_opts
     * @return array
     */
    private function _request($url, $curl_opts = array())
    {
        // Returned cached value
        if ($this->_cache_enabled && ($response = $this->_getCached($url))) {
            return $response;
        }
    
        // Merge the options (custom options take precedence).
        $curl_opts = $this->_curl_opts + $curl_opts + $this->CURL_DEFAULTS;
    
        // Call the API.
        $curl = curl_init($url);
        curl_setopt_array($curl, $curl_opts);
        $response = curl_exec($curl);
        $curl_info = curl_getinfo($curl);
    
        if (isset($curl_info['http_code']) && $curl_info['http_code'] === 0) {
            $curl_error = curl_error($curl);
            $curl_error = !empty($curl_error) ? '[' . $curl_error .']' : '';
    
            throw new VimeoRequestException('Unable to complete request.' . $curl_error);
        }
    
        curl_close($curl);
    
        // Retrieve the info
        $header_size = $curl_info['header_size'];
        $headers = substr($response, 0, $header_size);
        $body = substr($response, $header_size);
    
        $final_response = array(
            'body' => $body,
            'status' => $curl_info['http_code'],
            'headers' => self::parse_headers($headers)
        );
    
        if ($this->_cache_enabled) {
            $this->_cache($url, $final_response);
        }
    
        // Return it raw.
        return $final_response;
    }
    
    
    /**
     * Cache a response.
     *
     * @param string $url The parameters for the response.
     * @param string $response The serialized response data.
     */
    private function _cache($url, $response)
    {
        $hash = md5(serialize($url));
        $response = json_encode($response);
    
        if ($this->_cache_enabled == self::CACHE_FILE) {
                $file = $this->_cache_dir.'/'.$hash.'.cache';
            if (file_exists($file)) {
                unlink($file);
            }
            return file_put_contents($file, $response);
        }
    }
    
    /**
     * Get the unserialized contents of the cached request.
     *
     * @param array $url The full list of api parameters for the request.
     */
    private function _getCached($url)
    {
        $hash = md5(serialize($url));
        $expire =  86400;
    
        if ($this->_cache_enabled == self::CACHE_FILE) {
            $file = $this->_cache_dir.'/'.$hash.'.cache';
    
            if (file_exists($file)) {
                $last_modified = filemtime($file);
                if (substr($file, -6) == '.cache' && ($last_modified + $expire) < time()) {
                    unlink($file);
                }
              }
    
            if (file_exists($file)) {
                return json_decode(file_get_contents($file), true);
            }
    
        }
    }