colly_wyx
2018-04-27 74adf3a72663f151dc2c1b87ecb4ea4b0e080a50
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
/**
 * PhalApi_ModelProxy 模型Model代理 - 重量级数据获取的应对方案
 * 
 * - 结合缓存,进行对重量级成本高的数据进行缓冲读取
 * - 为了传递获取源数据而需要的参数,引入封装成值对象的PhalApi_ModelQuery查询对象
 * - 具体子类需要实现源数据获取、返回缓存唯一key、和返回有效期
 * - 仅在有需要的情况下,使用此Model代理
 *
 * <br>实例和使用示例:<br>
```
 * class ModelProxy_UserBaseInfo extends PhalApi_ModelProxy {
 *
 *      protected function doGetData($query) {
 *          $model = new Model_User();
 *      
 *          return $model->getByUserId($query->id);
 *      }
 *     
 *      protected function getKey($query) {
 *          return 'userbaseinfo_' . $query->id;
 *      }
 *     
 *      protected function getExpire($query) {
 *          return 600;
 *      }
 * }
 * 
 * //最终的调用
 * $query = new PhalApi_ModelQuery();
 * $query->id = $userId;
 * $modelProxy = new ModelProxy_UserBaseInfo();
 * $rs = $modelProxy->getData($query);
```
 *
 * @package     PhalApi\Model
 * @license     http://www.phalapi.net/license GPL 协议
 * @link        http://www.phalapi.net/
 * @author      dogstar <chanzonghuang@gmail.com> 2015-02-22
 */
 
abstract class PhalApi_ModelProxy {
    
    protected $cache;
 
    /**
     * 为代理指定委托的缓存组件,默认情况下使用DI()->cache
     */
    public function __construct(PhalApi_Cache $cache = NULL) {
        $this->cache = $cache !== NULL ? $cache : DI()->cache;
 
        //退而求其次
        if ($this->cache === NULL) {
            $this->cache = new PhalApi_Cache_None();
        }
    }
 
    /**
     * 获取源数据 - 模板方法
     *
     * @param PhalApi_ModelQuery $query 查询对象
     * @return mixed 返回源数据,但在失败的情况下别返回NULL,否则依然会穿透到此
     */
    public function getData(PhalApi_ModelQuery $query = NULL) {
        $rs = NULL;
 
        if ($query === NULL) {
            $query = new PhalApi_ModelQuery();
        }
 
        if ($query->readCache) {
            $rs = $this->cache->get($this->getkey($query));
            if ($rs !== NULL) {
                return $rs;
            }
        }
 
        // 这里,将获取耗性能的数据
        $rs = $this->doGetData($query);
 
        if ($query->writeCache) {
            $this->cache->set($this->getKey($query), $rs, $this->getExpire($query));
        }
 
        return $rs;
    }
    
    /**
     * 获取源数据 - 具体实现
     */
    abstract protected function doGetData($query);
 
    /**
     * 返回唯一缓存key,这里将$query传入,以便同类数据根据不同的值生成不同的key
     */
    abstract protected function getKey($query);
 
    /**
     * 返回缓存有效时间,单位为:秒
     */
    abstract protected function getExpire($query);
}