/**
* 读取或者设置缓存
* @access public
* @param string $key 缓存标识,支持变量规则 ,例如 item/:name/:id
* @param mixed $expire 缓存有效期
* @return mixed
*/
public function cache($key, $expire = null)
{
if ($this->isGet()) {
if (false !== strpos($key, ':')) {
$param = $this->param();
foreach ($param as $item => $val) {
if (is_string($val) && false !== strpos($key, ':' . $item)) {
$key = str_replace(':' . $item, $val, $key);
}
}
} elseif ('__URL__' == $key) {
// 当前URL地址作为缓存标识
$key = md5($this->url());
} elseif (strpos($key, ']')) {
if ('[' . $this->ext() . ']' == $key) {
// 缓存某个后缀的请求
$key = md5($this->url());
} else {
return;
}
}
if (strtotime($this->server('HTTP_IF_MODIFIED_SINCE')) + $expire > $_SERVER['REQUEST_TIME']) {
// 读取缓存
$response = Response::create()->code(304);
throw new \think\exception\HttpResponseException($response);
} elseif (Cache::has($key)) {
list($content, $header) = Cache::get($key);
$response = Response::create($content)->header($header);
throw new \think\exception\HttpResponseException($response);
} else {
$this->cache = [$key, $expire];
}
}
}