PHP编码二三事儿

来源:互联网 发布:java中的布尔类型 编辑:程序博客网 时间:2024/04/26 08:14

class_exists缺省情况下会触发autoload,如果你没注意到这点的话很可能会吃亏,演示代码:

spl_autoload_register(function($name) { echo $name; }); class_exists('foo');

你可以通过in_array($name, get_declared_classes())函数来判断是否存在相关的class,这样不会触发autoload,不过稍显笨重,其实class_exists()函数本身可以不触发autoload,方法是第二个参数:class_exists('foo', false);,不过老实说,当初设计的时候缺省值是true实在是个错误的决定。

BTW:method_exists也要注意,不过它没有类似class_exists那样能关闭autoload的参数控制,这一点在手册里已经明确写出来了,需要注意:

Note: Using this function will use any registered autoloaders if the class is not already known.

所以如果你不想触发autoload,那么在使用method_exists之前,必须确保对应的类已经加载,否则就没戏了。

缓存代码的重复味道

缓存在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方法,从而消除了重复的坏味道。

原创粉丝点击