ascetik/cacheable

将闭包和对象转换为字符串

v1.0.0 2023-11-11 10:59 UTC

This package is auto-updated.

Last update: 2024-09-11 12:41:03 UTC


README

将闭包和对象转换为字符串,以提供可调用的缓存

发布说明

v1.0.0

  • 重大变更:现在 CacheableCallascetik/callapsule 包扩展了 CallableType。方法已更新以匹配所需的行为。
  • CacheableCall 装饰一个 CallableType

目的

每次客户端切换页面或提交数据时,服务器都需要构建整个系统,包括服务、路由、中间件等。我想知道是否可以缓存一些实例或函数以加快系统构建。主要问题是闭包的序列化,这可能会被路由或服务容器使用。

需要很短的时间来找到 opis/closure 包。这是解决我问题的基础。此包可能仍然不完整。我必须在一个生产环境中对其进行测试,以获得一些带有日志的反馈。自制的记录器包还没有完成。

词汇表

Cacheable 是主要接口。它现在仅扩展 Serializable 接口,没有其他任何东西。 CacheableCall 抽象了能够序列化任何可调用的包装器的概念。 CacheableInstance 扩展了实例以使其完全可序列化。 CacheableProperty 保留每个 CacheableInstance 包装实例的名称和值。

描述和公开方法

注意:不推荐使用 serialize 和 unserialize 方法,并且肯定会导致序列化不一致。请使用本机 serialize/unserialize 函数。

CacheableFactory(而不是 Cacheable 本身)

  • wrapCall(callable):返回一个 CacheableCall 实例
  • wrapInstance(object):返回一个 CacheableInstance 实例
  • wrapProperty(string, mixed):返回一个 CacheableProperty

CacheableCall

  • action():返回已注册的可调用项
  • apply(iterable):调用已注册的可调用项

CacheableCall 可调用,以使其在运行时易于使用

CacheableInstance

  • getClass():返回注册的类名
  • getProperties():返回由注册实例属性构建的 CacheableProperties 容器
  • getInstance():返回注册的实例

CacheableProperty

  • getName():返回属性名称
  • getValue():返回属性值

用法

可调用包装

CacheableFactory 提供了构建可调用类型 Cacheable 实例的方法。有三种类型的包装器可以序列化可调用项

// Closure use case
$func = function(string $name): string {
    return 'Closure : hello '.$name;
}

// class method use case
class Greeter
{
    public function greet($name): string
    {
        return 'Method : hello ' . $name;
    }
}

// invokable class use case
class InvokableGreeter
{
    public function __invoke(string $name): string
    {
        return 'Invkable : hello ' . $name;
    }
}

$closureWrapper = CacheableFactory::wrapCall($func); // returns a CacheableClosure instance
$methodWrapper = CacheableFactory::wrapCall(new Greeter()); // returns a CacheableMethod instance
$invokableWrapper = CacheableFactory::wrapCall(new InvokableGreeter()); // returns a CacheableInvokable instance

因为它们都是 Cacheable,所以 Serializable,序列化很简单

$serial = serialize($closureWrapper);

反序列化也很简单

$serial = goAndFindInCache('something-satisfying-my-needs'); // file, external service, SQL, noSQL, hyper-speed keyboard typing world champion...
$wrapper = unserialize($serial);
echo $wrapper->apply(['John']); // prints 'Closure : hello John'
// A CacheableCall is invokable
echo $wrapper(['John']); // same result

实例包装

$instance = new MyInstance();
$wrapper = CacheableFactory::wrapInstance($instance);
$serial = serialize($wrapper);

// get wrapper back
$extractedWrapper = unserialize($serial);
$extractedInstance = $extractedWrapper->getInstance();
$extractedInstance->doWhatIsExpected();
// Or use the extracted wrapper directly
$extractedWrapper->doWhatIsExpected();
$property = $extractedWrapper->someProperty();

当使用包装器魔术方法时,如果

  • 调用的方法不存在,将引发异常
  • 属性不存在
  • 属性是公共的

结论

此包提供序列化和反序列化。使用输出的方式由您决定。