Skip to content

Instantly share code, notes, and snippets.

@dbernar1 dbernar1/gist:7893522
Last active Dec 30, 2015

Embed
What would you like to do?
A cute little cachable class method implementation
<?php
// Example:
$data_from_api = LibraryOfCachableFunctions::get_some_data_from_api( $args );
// LibraryOfCachableFunctions does not have a get_some_data_from_api() function.
// This causes __callStatic() to be called. __callStatic() takes care of caching.
// if the results are not available in the cache, it calls a function by adding an underscore to the name of the called function.
// the _get_some_data_from_api() function is used to obtain the results and store them in the cache.
// You can add any other cachable function simply by creating a function whose name starts with an underscore.
define( 'DEFAULT_CACHE_DURATION', 10 );
class LibraryOfCachableFunctions {
private static $cache_durations_in_minutes = array(
'get_some_data_from_api' => 60,
);
public static function __callStatic( $function_name, $arguments ) {
$cache_key = md5( $function_name . '?' . http_build_query( $arguments ) );
if ( cache_has( $cache_key ) {
return get_from_cache( $cache_key );
} else {
$data = call_user_func_array( array( 'self', '_' . $function_name ), $arguments );
$cache_duration = isset( self::$cache_durations_in_minutes[ $function_name ] ) ? self::$cache_durations_in_minutes[ $function_name ] : DEFAULT_CACHE_DURATION;
put_in_cache( $cache_key, $data, $cache_duration );
return $data;
}
}
private static function _get_some_data_from_api( $args ) {
// actually go to API
return array( '42' );
}
}
function cache_has( $key ) {
return false;
}
function get_from_cache( $key ) {
return null;
}
function put_in_cache( $key, $data, $duration_in_minutes ) {
return 'OK';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.