pinkcrab/memoize-trait

简单的Memoize基于对象缓存,用作特性。

1.0.1 2021-01-24 18:46 UTC

This package is auto-updated.

Last update: 2024-09-25 04:32:59 UTC


README

简单特性,用于将Memoize对象缓存添加到您的类中

alt text Open Source Love alt text alt text

版本

发布 1.0.0

为什么?

添加了一个具有memoize接口的内部缓存。根据调用时使用的参数的哈希值创建结果缓存。

设置

$ composer require pinkcrab/memoize-trait
use PinkCrab\Memoize\Memoizable;

class CategoryRepository {

    /**
     * Gives access to the Memoize cache
     */
    use Memoizable;

    /** 
     * Will call the database on the first call.
     * Creates a cache based on the hash of $id & $parent (concatinated)
     */
    public function getCategory($id, $parent): ?CategoryTerm {
        return $this->memoize(
            $this->generateHash($id, $parent),
            function () use ($id, $parent): ?CategoryTerm {
                return $this->slowDataSource->someExpensiveQuery($id, $parent);
            }
        )
    }
}

所有方法都是受保护的,并不是作为对象接口的一部分。

方法

memoize( string $hash, callable $fetch ): mixed

哈希值应该是唯一的、可重复的/纯的,基于参数。您可以使用内置的generateHash(...$scarla)。传递的可调用函数应在返回结果之前执行操作,然后将结果传递到内部缓存。

public function doExpensiveCall($param1, $param2): Result 
{
    return $this->memoize(
        // Generate Hash
        $this->generateHash($param1, $param2),
        // The fetch/call callable.
        function() use ($param1, $param2) : Result {
            return $this->service
                ->expensiveCall($param1, $param2);
        }
    );
}

generateHash(...$parts): string

允许传递任意数量的可序列化变量,并返回一个可重复的哈希值。这仅在底层使用MD5,您可以创建自定义哈希生成器

flushMemoize(): void

清除内部缓存数组。

依赖

  • --NONE--

许可证

MIT许可证

https://open-source.org.cn/licenses/mit-license.html

变更日志