Skip to content

Instantly share code, notes, and snippets.

@aphofstede
Last active April 13, 2018 11:10
Show Gist options
  • Save aphofstede/3144586 to your computer and use it in GitHub Desktop.
Save aphofstede/3144586 to your computer and use it in GitHub Desktop.
Cached function calling
/**
* 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;
}
@patricksavalle
Copy link

Put this in /system/libraries/Cache/Cached.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment