Skip to content

Instantly share code, notes, and snippets.

@ZAYEC77
Created September 23, 2016 17:49
Show Gist options
  • Save ZAYEC77/daa62054fdb6cb1354f4ce9ca44b686a to your computer and use it in GitHub Desktop.
Save ZAYEC77/daa62054fdb6cb1354f4ce9ca44b686a to your computer and use it in GitHub Desktop.
<?php
/**
*
* Example
*
* $result = Memoize::call([Product::className(), 'getSkuMap']); // slow operation
* $result2 = Memoize::call([Product::className(), 'getSkuMap']); // next call will be faster
*
* @author Dmytro Karpovych
* @copyright 2016 NRE
*/
namespace app\helpers;
class Memoize
{
protected static $cache = [];
/**
* @param $func
* @param array $args
* @return mixed
*/
public static function call($func, $args = [])
{
return call_user_func_array(self::get($func), $args);
}
public static function get($func)
{
$key = md5(serialize($func));
if (!array_key_exists($key, self::$cache)) {
self::$cache[$key] = self::getMemoize($func);
}
return self::$cache[$key];
}
/**
* @param $func
* @return \Closure
*/
public static function getMemoize($func)
{
return function () use ($func) {
static $cache = [];
$args = func_get_args();
$key = md5(serialize($args));
if (!array_key_exists($key, $cache)) {
$cache[$key] = call_user_func_array($func, $args);
}
return $cache[$key];
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment