zenstruck/memoize

用于高效缓存内存中昂贵方法的辅助特质。

资助包维护!
kbond

v0.1.0 2023-04-26 14:34 UTC

This package is auto-updated.

Last update: 2024-09-17 16:57:23 UTC


README

CI codecov

用于高效缓存内存中昂贵方法的辅助特质。

安装

composer require zenstruck/memoize

用法

将memoize特质添加到您希望缓存操作的对象中。

use Zenstruck\Memoize;

class MyObject
{
    use Memoize;

    public function method1(): mixed
    {
        // cache key defaults to the method name "method1"
        return $this->memoize(
            fn() => $this->someExpensiveOperation() // called only the first time method1() is called
        );
    }

    public function method2(): mixed
    {
        return $this->memoize(
            fn() => $this->someExpensiveOperation(),
            'my_custom_cache_key' // explicitly set the cache key
        );
    }

    public function method3(string $parameter): mixed
    {
        return $this->memoize(
            fn() => $this->someExpensiveOperation($parameter) // called once per unique parameter
            'my_custom_cache_key'.$parameter, // cache key includes the parameter
        )
    }

    public function refresh(): void
    {
        $this->clearMemoized(); // clear all cached values for this object instance
        $this->clearMemoized('method1'); // clear just the cached value for "method1"
    }
}

注意:缓存的值存储在以每个对象的实例为键的WeakMap中。当对象被垃圾回收时,它们会自动清除。