简单的mvc 框架(五)

现在来完善下 数据层(model+cache)
写个model类,用pdo来写

因为之前写过一个pdo操作类,http://blog.csdn.net/gongstrong123/article/details/50830934

就用这个操作类,但是封装的条件查询等操作方法可能不好,可以在根据业务需求再封装好一点

然后我们还有需要 加上上缓存操作,这里只做简单的查询缓存,
原理 :
查询的时候,首先在缓存里面查找,如果查找不到,在mysql里查找,再把查找结果集json_encode 存进缓存(redis),并且返回结果集,
当更新有缓存的数据表的时候,首先删除缓存里面该key的值,然后更新mysql。

缓存基本操作 connect set get

但是需要在model类操作缓存,需要在缓存操作类里面封装以下方法

public function setModel($model)
    {
        $this->model = new $model();
    }

    public function setMethod($method)
    {
        $this->method = $method;
    }

    public function selectFromCache($key)
    {
        $method = $this->method;
        $cache_result = $this->get($key);
        if ($cache_result === false) {
            $db_result = $this->model->$method($key);
            if ($db_result === false) {
                die('Data error');
            } else {
                if (is_array($db_result)) {
                    $db_result = json_encode($db_result);
                }
                if (!is_null($db_result)) {
                    $this->set($key, strval($db_result));
                }
            }
            return $db_result;
        } else {
            return $cache_result;
        }
    }

当model类需要用缓存的时候可以,写个缓存方法,然后写个MySQL数据库查询方法,实例:

 public function cache_getProfileInfo($uid)
    {
        $cache = BaseCache::getInstance();
        $cache->setModel('aModel');
        $cache->setMethod('getProfileInfo');
        $cache->selectFromCache($uid);
    }

    private function getProfileInfo($uid)
    {
        $table = 'user';
        $sql = sprintf('select *  from `user` where uid=%s', $uid);
        $res = $this->getRow($sql);
        return !$res ? false : $res;
    }

控制器直接调用cache_getProfileInfo ,查询缓存,缓存没有数据,则会返回MySQL里面的数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值