php 缓存代码的坏味道

缓存在Web程序里必不可少,最常见的形式如下:

01 class Foo extends DAO
02 {
03     public function find_by_a()
04     {
05         $result = $this->cache->get('cache_a');
06
07         if (!$result) {
08             $result = $this->db->getAll('select ... from ... where a ...');
09
10             $this->cache->set('cache_a', $result);
11         }
12
13         return $result;
14     }
15
16     public function find_by_b()
17     {
18         $result = $this->cache->get('cache_b');
19
20         if (!$result) {
21             $result = $this->db->getAll('select ... from ... where b ...');
22
23             $this->cache->set('cache_b', $result);
24         }
25
26         return $result;
27     }
28 }

这个代码很平常,实际情况中,多数人差不多都是这么写代码,先用某个键在缓存里取一下,如果没有就从数据库里实际查询一次,并且把结果缓存起来,这样的代码虽然不够健壮(没有捕捉可能存在的异常),不过本身并没有太大问题,但是若干个方法叠加起来,我们就能明显的感受到坏味道:重复!不说废话了哦,直接给出解决方案:

01 abstract class DAO
02 {
03     public function getCache($key, $closure)
04     {
05         $result = $this->cache->get($key);
06
07         if (!$result) {
08             $result = $closure();
09
10             $this->cache->set($key, $result);
11         }
12
13         return $result;
14     }
15 }
16
17 class Foo extends DAO
18 {
19     public function find_by_a()
20     {
21         return $this->getCache('cache_a', function() {
22             return $this->db->getAll('select ... from ... where a ...');
23         });
24     }
25
26     public function find_by_b()
27     {
28         return $this->getCache('cache_b', function() {
29             return $this->db->getAll('select ... from ... where b ...');
30         });
31     }
32 }

代码有点简陋,通过把非公共代码提取成一个closure,传递给getCache方法,从而消除了重复的坏味道。
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值