jarod8016b 发表于 2017-4-6 10:42:57

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方法,从而消除了重复的坏味道。
 
页: [1]
查看完整版本: php 缓存代码的坏味道