Last active
December 30, 2015 22:19
-
-
Save dbernar1/7893522 to your computer and use it in GitHub Desktop.
A cute little cachable class method implementation
This file contains 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 | |
// 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