Created
September 23, 2016 17:49
-
-
Save ZAYEC77/daa62054fdb6cb1354f4ce9ca44b686a to your computer and use it in GitHub Desktop.
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
<?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