PHP技巧:万能Cache
Web程序员最常使用的数据库封装方式就是DAO,其实和马丁大爷在PoEAA中所说的表数据入口差不多:
1 2 3 4 5 6 7 8 9 10 11 12 | class ArticleDAO { public function findById($id) { // SELECT * FROM article WHERE id = … } public function findByTitle($title) { // SELECT * FROM article WHERE title LIKE … } } |
如上所示,是一个最简单的DAO例子,为了提高效率,很多时候需要把查询结果都缓存起来:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | class ArticleCache { protected $cache; protected $dao; public function __construct($cache, $dao) { $this->cache = $cache; $this->dao = $dao; } public function findById($id) { $key = ‘id_’ . $id; if (!($result = $this->cache->get($key))) { $result = $this->cache->findById($id); $this->cache->set($key, $result); } return $result; } public function findByTitle($title) { $key = ‘title_’ . $title; if (!($result = $this->cache->get($key))) { $result = $this->cache->findByTitle($title); $this->cache->set($key, $result); } return $result; } } $memcache = new Memcache(); $memcache->connect(‘host’, ‘port’); $dao = new ArticleDAO(); $cache = new ArticleCache($memcache, $dao); $cache->findById(‘id’); $cache->findByTitle(‘title’); |
解决问题时,面向对象编程不变的伎俩就是引入新层,上面这个缓存功能的实现亦是如此,阿基米德当年叫嚷着:给我一个支点,我可以撬动地球;面向对象的粉丝 们也常有如此的豪言:加入一个新层,就可以实现任何功能。不过这里面出现了重复的坏味道,findById和findByTitle两个方法的实现代码大 体上是重复的,继续重构:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | class Cache { protected $cache; protected $dao; public function __construct($cache, $dao) { $this->cache = $cache; $this->dao = $dao; } public function __call($name, $arguments) { if (strtolower(substr($name, 0, 4)) != ‘find’) { return false; } $key = md5(strtolower(get_class($this->dao) . $name . serialize($arguments))); if (!($result = $this->cache->get($key, $flags))) { $result = call_user_func_array(array($this->dao, $name), $arguments); $this->cache->set($key, $result); } return $result; } } $memcache = new Memcache(); $memcache->connect(‘host’, ‘port’); $dao = new ArticleDAO(); $cache = new Cache($memcache, $dao); $cache->findById(‘id’); $cache->findByTitle(‘title’); |
通过使用魔术方法__call,我们成功的去除了重复代码,而且这个Cache可以说是“万能”的,因为除了ArticleDAO外,我们可能还有 CategoryDAO,CommentDAO等等,都可以用这个Cache来实现缓存。当然,Cache本身还不完善,有很多提升的余地,比如说缓存时 间的设置,或者内容更新时如何通过观察者模式的方式来完成缓存的主动更新等等,这些问题我就不得瑟了,留给读者自己思考。

