zenstruck / memoize
用于高效缓存内存中昂贵方法的辅助特质。
v0.1.0
2023-04-26 14:34 UTC
Requires
- php: >=8.0
Requires (Dev)
- phpstan/phpstan: ^1.4
- phpunit/phpunit: ^9.5.0
- symfony/phpunit-bridge: ^6.1
- symfony/var-dumper: ^5.4|^6.0
README
用于高效缓存内存中昂贵方法的辅助特质。
安装
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
中。当对象被垃圾回收时,它们会自动清除。