Skip to content

Instantly share code, notes, and snippets.

@ryun
Created April 18, 2012 00:38
Show Gist options
  • Save ryun/2410130 to your computer and use it in GitHub Desktop.
Save ryun/2410130 to your computer and use it in GitHub Desktop.
This demonstrates howto cache a static methods output. I use this "lazy method" for example: when I don't want to make multiple calls to the database
<?php
Class Example_Lib {
/**
* Internal cache helper
* Caches internal method results in memory
*
* @param string $func function to call
* @param array $args arguments for the callback function
* @return mixed
*/
private static function _cache($func, $args)
{
// re-index numerically
$args = array_values($args);
// create a key lookup
$key = sha1($func . serialize($args));
// check for cached item
if (isset(self::$CACHE[$key]))
{
return self::$CACHE[$key];
}
// Cache the out put of the call
self::$CACHE[$key] = call_user_func_array(array('self', $func), $args);
return self::$CACHE[$key];
}
/**
* Example cachable method
*/
public static function example()
{
return self::_cache('_example', func_get_args());
}
/**
* Actual method we are calling
*/
private static function _example($id)
{
$results = mysql_query('SELECT * FROM example_tbl');
return $result;
}
}
<?php
// Not cached
echo Example_Lib::example();
// cached
echo Example_Lib::example();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment