如果您不需要Type Safety,则可以使用通用的Cache Decorator:
class Cached
{
public function __construct($instance, $cacheDir = null)
{
$this->instance = $instance;
$this->cacheDir = $cacheDir === null ? sys_get_temp_dir() : $cacheDir;
}
public function defineCachingForMethod($method, $timeToLive)
{
$this->methods[$method] = $timeToLive;
}
public function __call($method, $args)
{
if ($this->hasActiveCacheForMethod($method, $args)) {
return $this->getCachedMethodCall($method, $args);
} else {
return $this->cacheAndReturnMethodCall($method, $args);
}
}
// … followed by private methods implementing the caching
然后,您将需要缓存的实例包装到此Decorator中,如下所示:
$cachedInstance = new Cached(new Instance);
$cachedInstance->defineCachingForMethod('foo', 3600);
如您所见,__ call方法还包含用于检查是否为该方法定义了缓存的代码.如果是这样,它将返回缓存的方法调用.如果没有,它将调用实例并缓存返回.
或者,您将专用的CacheBackend传递给Decorator,而不是在装饰器本身中实现缓存.然后,Decorator将仅作为装饰实例和后端之间的介体.
这种通用方法的缺点是您的缓存装饰器不具有装饰实例的类型.当您的消费代码需要Instance类型的实例时,您将收到错误.
如果您需要类型安全的装饰器,则需要使用“经典”方法:
>创建装饰实例公共API的接口.您可以手动执行此操作,如果需要大量工作,请使用我的Interface Distiller)
>将期望装饰实例的每个方法上的TypeHints更改为Interface
>让装饰实例实现它.
>让Decorator实现它并将任何方法委托给装饰实例
>修改所有需要缓存的方法
>对所有想要使用装饰器的类重复此操作
简而言之
class CachedInstance implements InstanceInterface
{
public function __construct($instance, $cachingBackend)
{
// assign to properties
}
public function foo()
{
// check cachingBackend whether we need to delegate call to $instance
}
}
缺点是,这是更多的工作.您需要为每个应该使用缓存的类执行此操作.您还需要将检查放入缓存后端到每个函数(代码复制),以及将任何不需要缓存的调用委托给装饰实例(繁琐且容易出错).