现在来完善下 数据层(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里面的数据