php装饰器模式返回数据格式,在PHP中实现方法结果缓存的装饰器模式的最佳方法...

如果您不需要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

}

}

缺点是,这是更多的工作.您需要为每个应该使用缓存的类执行此操作.您还需要将检查放入缓存后端到每个函数(代码复制),以及将任何不需要缓存的调用委托给装饰实例(繁琐且容易出错).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值