antevenio/memoize

内存函数缓存,可以限制总内存消耗和每个函数的TTL。

0.0.16 2019-09-09 07:48 UTC

This package is auto-updated.

Last update: 2024-09-19 19:34:39 UTC


README

Latest Stable Version Total Downloads License Travis build Coverage Status Maintainability

另一个内存函数缓存库。

特性

  • 可以指定缓存保留的项目最大数量。
  • 可以为每个可调用项指定TTL(存活时间)。(这意味着memoize将在TTL过期之前返回缓存的调用结果,在这种情况下,它将再次调用函数并生成新的缓存结果)
  • 可以覆盖默认的可调用参数缓存索引以使用自定义索引。(如果您想这样做,即使传递不同的参数也可以重用缓存的调用项)
  • 缓存抛出的异常。

行为

  • 当达到缓存中的项目最大数量时,它将首先驱逐最旧的(最先缓存的)可调用项。

要求

以下PHP版本得到支持。

  • PHP 5.6
  • PHP 7.0
  • PHP 7.1
  • PHP 7.2
  • PHP 7.3

安装

composer require antevenio/memoize

用法

常见代码

<?php
require_once('./vendor/autoload.php');

use Antevenio\Memoize\Memoizable;
use Antevenio\Memoize\Memoize;
use Antevenio\Memoize\Cache;

class Toolbox
{
    public function multiply($argument)
    {
        echo "Called with {$argument}\n";

        return $argument * 2;
    }
    
    public function throwException($argument)
    {
        echo "Called with {$argument}\n";

        throw new \Exception($argument);
    }
}

$toolbox = new Toolbox();
$memoize = new Memoize((new Cache())->setEntryLimit(100));

基本

for ($i = 0; $i < 10; $i++) {
    $result = $memoize->memoize(
        (new Memoizable([$toolbox, 'multiply'], [10]))->withTtl(5)
    );
    echo "Result: $result\n";
    sleep(1);
}

->>>

Called with 10
Result: 20
Result: 20
Result: 20
Result: 20
Result: 20
Called with 10
Result: 20
Result: 20
Result: 20
Result: 20
Result: 20

更改参数

for ($i = 0; $i < 10; $i++) {
    $result = $memoize->memoize(
        (new Memoizable([$toolbox, 'multiply'], [$i % 2]))->withTtl(5)
    );
    echo "Result: $result\n";
    sleep(1);
}

->>>

Called with 0
Result: 0
Called with 1
Result: 2
Result: 0
Result: 2
Result: 0
Result: 2
Called with 0
Result: 0
Called with 1
Result: 2
Result: 0
Result: 2

自定义索引

for ($i = 0; $i < 10; $i++) {
    $result = $memoize->memoize(
        (new Memoizable([$toolbox, 'multiply'], [$i]))->withTtl(5)->withCustomIndex('myFixedIndex')
    );
    echo "Result: $result\n";
    sleep(1);
}

->>>

Called with 0
Result: 0
Result: 0
Result: 0
Result: 0
Result: 0
Called with 5
Result: 10
Result: 10
Result: 10
Result: 10
Result: 10

异常

for ($i = 0; $i < 10; $i++) {
    $result = $memoize->memoize(
        (new Memoizable([$toolbox, 'throwException'], ['foo']))->withTtl(5)
    );
    echo "Result: $result\n";
    sleep(1);
}

->>>

Called with foo
Thrown exception foo
Thrown exception foo
Thrown exception foo
Thrown exception foo
Thrown exception foo
Called with foo
Thrown exception foo
Thrown exception foo
Thrown exception foo
Thrown exception foo
Thrown exception foo