Welcome Guest, Not a member yet? Register   Sign In
Varnish library with support for cache purging
#1

[eluser]mptre[/eluser]
Hello,
I recently wrote a real simple Varnish library with support for cache purging. Hope someone finds it useful!

Code:
<?php
/**
* Varnish CodeIgniter utils.
*
* @author Anton Lindqvist <[email protected]>
* @copyright 2010 Anton Lindqvist <[email protected]>
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://gist.github.com/gists/727012
*/
class Varnish {

    /**
     * cURL default options.
     *
     * @access private
     *
     * @var array
     */
    private static $_curl_default_options = array(
        CURLOPT_HEADER => false,
        CURLOPT_RETURNTRANSFER => true
    );

    /**
     * cURL purge options.
     *
     * @access private
     *
     * @var array
     */
    private static $_curl_purge_options = array(
        CURLOPT_CUSTOMREQUEST => 'PURGE',
        CURLOPT_FORBID_REUSE => true
    );

    /**
     * Purge a given URI.
     *
     * @param string $uri
     *
     * @return boolean
     * @see Varnish::_curl()
     */
    function purge($uri) {
        if (!preg_match('/^https?\:\/\//', $uri)) {
            $uri = trim(base_url(), '/') . $uri;
        }

        return ($this->_curl($uri, self::$_curl_purge_options))
            ? true
            : false;
    }

    /**
     * Perform an HTTP request using cURL.
     *
     * @param string $url The URL to request
     * @param array $options Optional cURL options.
     *
     * @return mixed
     */
    private function _curl($url, $options = null) {
        $ch = curl_init($url);

        if (is_array($options) && count($options)) {
            foreach (self::$_curl_default_options as $key => $val) {
                if (!array_key_exists($key, $options)) {
                    $options[$key] = $val;
                }
            }
        } else {
            $options = self::$_curl_default_options;
        }

        curl_setopt_array($ch, $options);

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        return (preg_match('/^2[0-9]{2}$/', (string)$http_code))
            ? $response
            : false;
    }

}
#2

[eluser]sp2hari[/eluser]
Can you tell me how this works and how the cache purge happens?




Theme © iAndrew 2016 - Forum software by © MyBB