一个用于缓存重复函数调用的库。

v3.0.0 2024-08-13 15:23 UTC

This package is auto-updated.

Last update: 2024-09-13 15:39:40 UTC


README

一个用于缓存重复函数调用的PHP库。

Build Status Scrutinizer Code Quality Code Coverage

Latest Stable Version Total Downloads License

需求

此库需要PHP 7.0或更高版本。

安装

此包使用 composer,因此您只需将 traderinteractive/memoize 添加为 composer.json 文件中的依赖项即可。

缓存

缓存 是一种通过缓存函数调用的结果来优化重复调用的函数的方法。

缓存提供者

此库包括几个内置的缓存提供者。每个都实现了 \TraderInteractive\Memoize\Memoize 接口

interface Memoize
{
    /**
     * Gets the value stored in the cache or uses the passed function to
     * compute the value and save to cache.
     *
     * @param string $key The key to fetch
     * @param callable $compute A function to run if the value was not cached
     *     that will return the result.
     * @param int $cacheTime The number of seconds to cache the response for,
     *     or null to not expire it ever.
     * @return mixed The data requested, optionally pulled from cache
     */
    public function memoizeCallable($key, $compute, $cacheTime = null);
}

$compute 可调用函数不得接受任何参数 - 如果您需要参数,请考虑将您的函数包装在闭包中,并将所需的参数引入作用域。例如,给定函数

$getUser = function($database, $userId) {
  $query = $database->select('*')->from('user')->where(['id' => $userId]);
  return $query->fetchOne();
};

您可以将它这样包装在闭包中

$getLoggedInUser = function() use($database, $loggedInUserId, $getUser) {
    return $getUser($database, $loggedInUserId);
};

$memoize->memoizeCallable("getUser-{$loggedInUserId}", $getLoggedInUser);

或者,您可以反过来操作,返回闭包,如下所示

$getUserLocator = function($database, $userId) use($getUser) {
    return function() use($database, $userId, $getUser) {
        return $getUser($database, $userId);
    };
};

$getLoggedInUser = $getUserLocator($database, $loggedInUserId);
$memoize->memoizeCallable("getUser-{$loggedInUserId}", $getLoggedInUser);

此库的将来版本可能会添加对参数的支持,因为这是一个常见的用例(尤其是递归函数时)。

还值得注意,您需要确保为使用缓存器的一切定义唯一的缓存键。

Predis

Predis 提供者使用 predis 库在 Redis 中缓存结果。它支持 $cacheTime 参数,以便在时间过期后重新计算结果。

此缓存器可以用作在进程间持久化的方式,而不仅仅是缓存当前进程的计算。

示例

$predis = new \Predis\Client($redisUrl);
$memoize = new \TraderInteractive\Memoize\Predis($predis);

$compute = function() {
    // Perform some long operation that you want to memoize
};

// Cache he results of $compute for 1 hour.
$result = $memoize->memoizeCallable('myLongOperation', $compute, 3600);

内存

这是一个标准的内存缓存器。目前不支持 $cacheTime,并且仅在缓存器在内存中的时候保留结果。

示例

$memoize = new \TraderInteractive\Memoize\Memory();

$compute = function() {
    // Perform some long operation that you want to memoize
};

$result = $memoize->memoizeCallable('myLongOperation', $compute);

此缓存器实际上不缓存任何内容 - 它始终调用 $compute 函数。它对于测试很有用,也可以在您禁用缓存以进行调试等时使用,因为您可以将实际的缓存器替换为这个,一切仍然可以正常工作。

示例

$memoize = new \TraderInteractive\Memoize\None();

$compute = function() {
    // Perform some long operation that you want to memoize
};

// This will never actually memoize the results - they will be recomputed every
// time.
$result = $memoize->memoizeCallable('myLongOperation', $compute);