3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
21 class CacheException
extends Exception
{
26 public function getRequestTime() {
27 return $_SERVER['REQUEST_TIME'];
40 private $storage = null;
45 static public function createCache($cacheClass, $name, RequestTime
$time = null) {
46 return new Cache($cacheClass, $name, $time);
49 private function __construct($cacheClass, $name, RequestTime
$time = null) {
50 $this->storage
= new $cacheClass($name);
52 $this->time
= new RequestTime();
58 public function get($key) {
59 if ($this->storage
->isLocked($key)) {
60 $this->storage
->waitForLock($key);
62 $data = $this->storage
->fetch($key);
64 $data = unserialize($data);
65 if ($data['valid'] && ($this->time
->getRequestTime() - $data['time']) < $data['ttl']) {
72 public function expiredGet($key) {
73 if ($this->storage
->isLocked($key)) {
74 $this->storage
->waitForLock($key);
76 $data = $this->storage
->fetch($key);
78 $data = unserialize($data);
79 return array_merge(array('found' => true), $data);
81 return array('found' => false);
84 public function set($key, $value, $ttl = false) {
86 $ttl = Config
::Get('cache_time');
88 if ($this->storage
->isLocked($key)) {
89 $this->storage
->waitForLock($key);
91 $data = serialize(array('time' => $this->time
->getRequestTime(), 'ttl' => $ttl, 'valid' => true, 'data' => $value));
92 $this->storage
->lock($key);
94 $this->storage
->store($key, $data);
95 $this->storage
->unlock($key);
96 } catch (Exception
$e) {
97 $this->storage
->unlock($key);
102 public function delete($key) {
103 if ($this->storage
->isLocked($key)) {
104 $this->storage
->waitForLock($key);
106 $this->storage
->lock($key);
107 $this->storage
->delete($key);
108 $this->storage
->unlock($key);
111 public function invalidate($key) {
112 if ($this->storage
->isLocked($key)) {
113 $this->storage
->waitForLock($key);
115 $this->storage
->lock($key);
117 $data = $this->storage
->fetch($key);
119 $data = unserialize($data);
120 $data = serialize(array('time' => $data['time'], 'ttl' => $data['ttl'], 'valid' => false, 'data' => $data['data']));
121 $this->storage
->store($key, $data);
123 $this->storage
->unlock($key);
124 } catch (Exception
$e) {
125 $this->storage
->unlock($key);