PHP 中的缓存函数结果

发布于 2024-09-16 03:13:11 字数 546 浏览 7 评论 0原文

我正在制作一个简单的工具来缓存函数结果

它看起来像:(

global $function_results;
$function_results = array();

function getMembers($conditions, $default = array('order' => 'name', array('abc', 'def'))){

    //****Help need from here******
    //make unique id from parameters value and function name
    //ex: $uid;
    //****to here******

    global $function_results;
    if(isset($function_results[$uid])) return $function_results[$uid];
    else{
        //do function logic...
    }
}

函数及其参数只是一个示例)

有什么建议吗?

I'm making a simple tool to cache function results

It look like:

global $function_results;
$function_results = array();

function getMembers($conditions, $default = array('order' => 'name', array('abc', 'def'))){

    //****Help need from here******
    //make unique id from parameters value and function name
    //ex: $uid;
    //****to here******

    global $function_results;
    if(isset($function_results[$uid])) return $function_results[$uid];
    else{
        //do function logic...
    }
}

(the function and its parameters are just an example)

Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

淡写薰衣草的香 2024-09-23 03:13:12

这是您缺少的代码:

$numargs = func_num_args();
$arg_list = func_get_args();
$md5this = '';
for ($i = 0; $i < $numargs; $i++) {
    $md5this .= $i.':'.serialize($arg_list[$i]).';';
}
$uid = md5($md5this);

供您参考: http://php.net /manual/en/function.func-get-args.php

Here is your missing code:

$numargs = func_num_args();
$arg_list = func_get_args();
$md5this = '';
for ($i = 0; $i < $numargs; $i++) {
    $md5this .= $i.':'.serialize($arg_list[$i]).';';
}
$uid = md5($md5this);

For your reference: http://php.net/manual/en/function.func-get-args.php

作死小能手 2024-09-23 03:13:12

这是一个与 PHP 5.2.x 兼容的通用记忆化解决方案。

call_memoized 函数:

  1. 根据函数名称和参数生成唯一的缓存键。
  2. 如果缓存为空,则调用该函数并用结果更新缓存。
  3. 返回缓存的值。

不要直接使用 call_memoized,而是使用提供的 memoize 函数,该函数返回给定函数的新版本,该函数将自动缓存相同参数组合的结果。

请参阅下面的示例。

享受!

global $MEMO_CACHE;
$MEMO_CACHE = array();

/** Returns the result of the function with the given arguments. 
 * Invokes the function only once, thereafter returns the result 
 * cached by a key based on the function name and arguments. */
function call_memoized($fun, $args=array()) {
    global $MEMO_CACHE;

    // generate a cache key based on the function name and arguments
    $uid = md5(
        implode("|", array_merge((array)$fun, array_map(
            "serialize",
            $args)
        ))
    );

    // if there result hasn't been cached, call the function 
    // and update the cache with the result.
    if(!array_key_exists($uid, $MEMO_CACHE)) {
        $MEMO_CACHE[$uid] = call_user_func_array($fun, $args);
    }

    return $MEMO_CACHE[$uid];
}

/** Returns a memoized version of the given function that will cache 
 * its results for each unique set of inputs. */
function memoize($fun) {
    return create_function(
        '', 
        "\$args = func_get_args(); return call_memoized('$fun', \$args);"
    );
}

示例:

/** Returns a random number with the given greeting. */
function random($greeting) {
    return "$greeting! " . rand();
};

print("Five random numbers:</br />");
for($i=0; $i<5; $i++) {
    print(random("Spin the wheel") . "<br />");
}
print "<br />";

print("After memoizing the random function, it's not so random:<br />");
$not_so_random = memoize("random");
for($i=0; $i<5; $i++) {
    print($not_so_random("Spin the wheel") . "<br />");
}
print "<br />";

print("The same memoized function is invoked with a different argument, and 
       thus creates a different cache key:<br />");
for($i=0; $i<5; $i++) {
    print($not_so_random("Twirl the tire") . "<br />");
}

/* OUTPUT

Five random numbers:
Spin the wheel! 26488
Spin the wheel! 20049
Spin the wheel! 14006
Spin the wheel! 28599
Spin the wheel! 804

After memoizing the random function, it's not so random:
Spin the wheel! 32397
Spin the wheel! 32397
Spin the wheel! 32397
Spin the wheel! 32397
Spin the wheel! 32397

The same memoized function is invoked with a different argument, and 
thus creates a different cache key:
Twirl the tire! 2114
Twirl the tire! 2114
Twirl the tire! 2114
Twirl the tire! 2114
Twirl the tire! 2114
*/

Here is a generic memoization solution that is compatible with PHP 5.2.x.

The call_memoized function:

  1. Generates a unique cache key based on the function name and arguments.
  2. If the cache is empty, invokes the function and updates the cache with the result.
  3. Returns the cached value.

Instead of using call_memoized directly, use the provided memoize function, which returns a new version of the given function that will automatically cache results from the same combination of parameters.

See example below.

Enjoy!

global $MEMO_CACHE;
$MEMO_CACHE = array();

/** Returns the result of the function with the given arguments. 
 * Invokes the function only once, thereafter returns the result 
 * cached by a key based on the function name and arguments. */
function call_memoized($fun, $args=array()) {
    global $MEMO_CACHE;

    // generate a cache key based on the function name and arguments
    $uid = md5(
        implode("|", array_merge((array)$fun, array_map(
            "serialize",
            $args)
        ))
    );

    // if there result hasn't been cached, call the function 
    // and update the cache with the result.
    if(!array_key_exists($uid, $MEMO_CACHE)) {
        $MEMO_CACHE[$uid] = call_user_func_array($fun, $args);
    }

    return $MEMO_CACHE[$uid];
}

/** Returns a memoized version of the given function that will cache 
 * its results for each unique set of inputs. */
function memoize($fun) {
    return create_function(
        '', 
        "\$args = func_get_args(); return call_memoized('$fun', \$args);"
    );
}

Example:

/** Returns a random number with the given greeting. */
function random($greeting) {
    return "$greeting! " . rand();
};

print("Five random numbers:</br />");
for($i=0; $i<5; $i++) {
    print(random("Spin the wheel") . "<br />");
}
print "<br />";

print("After memoizing the random function, it's not so random:<br />");
$not_so_random = memoize("random");
for($i=0; $i<5; $i++) {
    print($not_so_random("Spin the wheel") . "<br />");
}
print "<br />";

print("The same memoized function is invoked with a different argument, and 
       thus creates a different cache key:<br />");
for($i=0; $i<5; $i++) {
    print($not_so_random("Twirl the tire") . "<br />");
}

/* OUTPUT

Five random numbers:
Spin the wheel! 26488
Spin the wheel! 20049
Spin the wheel! 14006
Spin the wheel! 28599
Spin the wheel! 804

After memoizing the random function, it's not so random:
Spin the wheel! 32397
Spin the wheel! 32397
Spin the wheel! 32397
Spin the wheel! 32397
Spin the wheel! 32397

The same memoized function is invoked with a different argument, and 
thus creates a different cache key:
Twirl the tire! 2114
Twirl the tire! 2114
Twirl the tire! 2114
Twirl the tire! 2114
Twirl the tire! 2114
*/
往日情怀 2024-09-23 03:13:12

我想 $conditions 是一些值的数组,并且您想为该数组的每个变体创建唯一标识符?有几种方法可以做到这一点,例如:

$uid = md5(serialize($conditions));

I suppose $conditions is an array of some values and you want to create a unique identifier for each variant of that array? There is several ways to do that, eg.:

$uid = md5(serialize($conditions));
西瓜 2024-09-23 03:13:12

查看 memoized 函数实现 Nspl

function memoized(callable $function)
{
    return function() use ($function) {
        static $memory = array();
        $args = func_get_args();
        $key = serialize($args);
        if (!isset($memory[$key]) && !array_key_exists($key, $memory)) {
            $memory[$key] = call_user_func_array($function, $args);
        }

        return $memory[$key];
    };
}

或者,如果您在服务器请求之间寻找缓存函数结果,则可以使用 Cachalot

$cache = new \Cachalot\ApcCache();
$result = $cache->getCached($function, $args);

支持不同的后端:Apc、Xcache、Memcached、Redis、Couchbase。

Have a look at memoized function implementation from Nspl:

function memoized(callable $function)
{
    return function() use ($function) {
        static $memory = array();
        $args = func_get_args();
        $key = serialize($args);
        if (!isset($memory[$key]) && !array_key_exists($key, $memory)) {
            $memory[$key] = call_user_func_array($function, $args);
        }

        return $memory[$key];
    };
}

Or if you looking for caching function results between server requests you can use Cachalot:

$cache = new \Cachalot\ApcCache();
$result = $cache->getCached($function, $args);

Different back-ends are supported: Apc, Xcache, Memcached, Redis, Couchbase.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文