Created
January 25, 2011 16:28
-
-
Save felipelavinz/795161 to your computer and use it in GitHub Desktop.
An abstract class to facilitate working with WordPress transients
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
abstract class av_transients_helper{ | |
var $transient_name; | |
var $expire; | |
function __construct($id, $expire){ | |
$this->transient_name = $id; | |
$_expire = ( (int)$expire > 0 ) ? (int)$expire : 1; | |
$this->transient_expire = 60 * 60 * $_expire; | |
} | |
public function get_data(){ | |
$_transient_data = $this->get_transient(); | |
if ( $_transient_data ) | |
return $_transient_data; | |
else | |
return $this->refresh_data(); | |
} | |
private function get_transient(){ | |
$_transient = get_transient($this->transient_name); | |
if ( $_transient ) | |
return maybe_unserialize($_transient); | |
else | |
return false; | |
} | |
private function refresh_data(){ | |
$raw = $this->get_external_data(); | |
if ( $raw ) return $this->set_transient($raw); | |
else return false; | |
} | |
/** | |
* Get data from external API | |
* @uses WP_Http WordPress HTTP request class | |
* @return Raw API Data; false on failure | |
**/ | |
private function get_external_data(){ | |
if ( !class_exists( 'WP_Http') ) require_once( ABSPATH . WPINC . '/class-http.php' ); | |
$request = new WP_Http; | |
$request_url = $this->build_request_url(); | |
$result = $request->request($request_url); | |
if ( is_array($result['response']) && $result['response']['code'] == 200 ) return $result['body']; | |
else return false; | |
} | |
/** | |
* @return API Request URI | |
**/ | |
abstract function build_request_url(); | |
/** | |
* @param string $data RAW API Response | |
* @return object Easier to manage data to save in the transient | |
**/ | |
abstract function prepare_data($data); | |
/** | |
* Save transient data | |
* @param object $raw Raw API Response | |
* @return object Parsed, stripped down data, false on failure | |
**/ | |
private function set_transient($raw){ | |
$transient_data =& $this->prepare_data($raw); | |
if ( $transient_data ) { | |
if ( set_transient($this->transient_name, $transient_data, $this->transient_expire) ) | |
return $transient_data; | |
else | |
return false; | |
} else { | |
return false; | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment