Last active
April 13, 2018 11:10
-
-
Save aphofstede/3144586 to your computer and use it in GitHub Desktop.
Cached function calling
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
/** | |
* call_user_func_array_cached | |
* | |
* @param function, variable args | |
* @return object | |
*/ | |
function call_user_func_array_cached( $function, $param_arr ) | |
{ | |
// ---------------------------------------------------------- | |
// Cached version of call_user_func_array, use only for TRUE | |
// function, i.e. function whose result only depend on args | |
// ---------------------------------------------------------- | |
if ( is_array( $function ) ) | |
{ | |
if ( is_object( $function[0] ) ) | |
{ | |
$mangled_name = 'obj'. get_class( $function[0] ) . | |
$function[1] . serialize( $param_arr ); | |
} | |
else | |
{ | |
$mangled_name = $function[0] . $function[1] . | |
serialize( $param_arr ); | |
} | |
} | |
else | |
{ | |
$mangled_name = $function . serialize( $param_arr ); | |
} | |
$cache_key = md5( __CLASS__ . $mangled_name ); | |
// ------------------------------------------------------------------ | |
// Mangle function signature and try to get from cache | |
// ------------------------------------------------------------------ | |
$result = $this->get( $cache_key ); | |
if ( empty( $result) ) | |
{ | |
// ------------------------------------------------------------------ | |
// If not, call the function and get the result, we can only | |
// cachify methods of subclasses of this class | |
// ------------------------------------------------------------------ | |
$result = call_user_func_array( $function, $param_arr ); | |
// ------------------------------------------------------------------ | |
// Store the result in the cache for next time | |
// ------------------------------------------------------------------ | |
$this->save( $cache_key, $result ); | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Put this in /system/libraries/Cache/Cached.php