thinkphp链接缓存函数,支持model的所有函数方法

在thinkphp里,链接缓存函数只有cache,如$Model->cache(true)->select();

但只支持select方法和其派生的函数,

这里我改了一下缓存方法,可以用D和M方法调用的任意函数

文件/common/cacheModel.php

 1 <?php
 2 
 3 /**
 4  * 缓存模型函数 CacheModel
 5  * 继承用于缓存D方法的函数
 6  * @author wang
 7  */
 8 class CacheModel extends Model{
 9 
10     /**
11      * 缓存方法的链式函数
12      * @param int $expre 缓存时间,默认4个小时,0为删除缓存
13      * @param string $key 缓存名,默认使用md5值
14      * @return \functionCache class
15      */
16     public function funCache($expire = 14400, $key = null){
17         return new functionCache($this, $expire, $key);
18     }
19 
20 }
21 
22 /**
23  * 模型函数缓存 functionCache
24  * 缓存function
25  * @author wang
26  */
27 class functionCache{
28 
29     var $model = null;
30     var $expire = null;
31     var $key = null;
32 
33     function __construct($fun, $expire, $key){
34         $this->model = $fun;
35         $this->expire = $expire;
36         $this->key = $key;
37     }
38 
39     function __call($name, $arguments){
40         !is_string($this->key) and $this->key = md5($name . json_encode($arguments, PHP_VERSION_ID < 50303 ? 0 : JSON_NUMERIC_CHECK));
41 
42         if($this->expire <= 0){
43             return S($this->key, null);
44         }
45 
46         $value = S($this->key);
47         if(false !== $value){
48             return $value;
49         }
50 
51         if(method_exists($this->model, $name)){
52             $result = call_user_func_array(array($this->model, $name), $arguments);
53         }else{
54             throw_exception(__CLASS__ . ':' . $name . L('_METHOD_NOT_EXIST_'));
55         }
56         if(!empty($result)){
57             S($this->key, $result, $this->expire);
58         }
59         return $result;
60     }
61 
62 }

在config.php引用'LOAD_EXT_FILE' => 'CacheModel',(这里用任何thinkphp支持的方法引用都行)

然后写model的时改写其extends如:

class AclModel extends CacheModel{}

调用示例

1 //缓存函数
2 D('Acl')->funCache()->getAuth($userId);
3 //删除缓存,注意后面的参数要一样,
4 D('Acl')->funCache(0)->getAuth($userId);
5 //缓存查询
6 M('Acl')->funCache()->find();

 

posted @ 2013-05-27 22:27  无嗔  阅读(973)  评论(0编辑  收藏  举报