528 lines
23KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\caching;
  8. use yii\base\Component;
  9. use yii\helpers\StringHelper;
  10. /**
  11. * Cache is the base class for cache classes supporting different cache storage implementations.
  12. *
  13. * A data item can be stored in the cache by calling [[set()]] and be retrieved back
  14. * later (in the same or different request) by [[get()]]. In both operations,
  15. * a key identifying the data item is required. An expiration time and/or a [[Dependency|dependency]]
  16. * can also be specified when calling [[set()]]. If the data item expires or the dependency
  17. * changes at the time of calling [[get()]], the cache will return no data.
  18. *
  19. * A typical usage pattern of cache is like the following:
  20. *
  21. * ```php
  22. * $key = 'demo';
  23. * $data = $cache->get($key);
  24. * if ($data === false) {
  25. * // ...generate $data here...
  26. * $cache->set($key, $data, $duration, $dependency);
  27. * }
  28. * ```
  29. *
  30. * Because Cache implements the [[\ArrayAccess]] interface, it can be used like an array. For example,
  31. *
  32. * ```php
  33. * $cache['foo'] = 'some data';
  34. * echo $cache['foo'];
  35. * ```
  36. *
  37. * Derived classes should implement the following methods which do the actual cache storage operations:
  38. *
  39. * - [[getValue()]]: retrieve the value with a key (if any) from cache
  40. * - [[setValue()]]: store the value with a key into cache
  41. * - [[addValue()]]: store the value only if the cache does not have this key before
  42. * - [[deleteValue()]]: delete the value with the specified key from cache
  43. * - [[flushValues()]]: delete all values from cache
  44. *
  45. * @author Qiang Xue <qiang.xue@gmail.com>
  46. * @since 2.0
  47. */
  48. abstract class Cache extends Component implements \ArrayAccess
  49. {
  50. /**
  51. * @var string a string prefixed to every cache key so that it is unique globally in the whole cache storage.
  52. * It is recommended that you set a unique cache key prefix for each application if the same cache
  53. * storage is being used by different applications.
  54. *
  55. * To ensure interoperability, only alphanumeric characters should be used.
  56. */
  57. public $keyPrefix;
  58. /**
  59. * @var null|array|false the functions used to serialize and unserialize cached data. Defaults to null, meaning
  60. * using the default PHP `serialize()` and `unserialize()` functions. If you want to use some more efficient
  61. * serializer (e.g. [igbinary](http://pecl.php.net/package/igbinary)), you may configure this property with
  62. * a two-element array. The first element specifies the serialization function, and the second the deserialization
  63. * function. If this property is set false, data will be directly sent to and retrieved from the underlying
  64. * cache component without any serialization or deserialization. You should not turn off serialization if
  65. * you are using [[Dependency|cache dependency]], because it relies on data serialization. Also, some
  66. * implementations of the cache can not correctly save and retrieve data different from a string type.
  67. */
  68. public $serializer;
  69. /**
  70. * Builds a normalized cache key from a given key.
  71. *
  72. * If the given key is a string containing alphanumeric characters only and no more than 32 characters,
  73. * then the key will be returned back prefixed with [[keyPrefix]]. Otherwise, a normalized key
  74. * is generated by serializing the given key, applying MD5 hashing, and prefixing with [[keyPrefix]].
  75. *
  76. * @param mixed $key the key to be normalized
  77. * @return string the generated cache key
  78. */
  79. public function buildKey($key)
  80. {
  81. if (is_string($key)) {
  82. $key = ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);
  83. } else {
  84. $key = md5(json_encode($key));
  85. }
  86. return $this->keyPrefix . $key;
  87. }
  88. /**
  89. * Retrieves a value from cache with a specified key.
  90. * @param mixed $key a key identifying the cached value. This can be a simple string or
  91. * a complex data structure consisting of factors representing the key.
  92. * @return mixed the value stored in cache, false if the value is not in the cache, expired,
  93. * or the dependency associated with the cached data has changed.
  94. */
  95. public function get($key)
  96. {
  97. $key = $this->buildKey($key);
  98. $value = $this->getValue($key);
  99. if ($value === false || $this->serializer === false) {
  100. return $value;
  101. } elseif ($this->serializer === null) {
  102. $value = unserialize($value);
  103. } else {
  104. $value = call_user_func($this->serializer[1], $value);
  105. }
  106. if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->getHasChanged($this))) {
  107. return $value[0];
  108. } else {
  109. return false;
  110. }
  111. }
  112. /**
  113. * Checks whether a specified key exists in the cache.
  114. * This can be faster than getting the value from the cache if the data is big.
  115. * In case a cache does not support this feature natively, this method will try to simulate it
  116. * but has no performance improvement over getting it.
  117. * Note that this method does not check whether the dependency associated
  118. * with the cached data, if there is any, has changed. So a call to [[get]]
  119. * may return false while exists returns true.
  120. * @param mixed $key a key identifying the cached value. This can be a simple string or
  121. * a complex data structure consisting of factors representing the key.
  122. * @return boolean true if a value exists in cache, false if the value is not in the cache or expired.
  123. */
  124. public function exists($key)
  125. {
  126. $key = $this->buildKey($key);
  127. $value = $this->getValue($key);
  128. return $value !== false;
  129. }
  130. /**
  131. * Retrieves multiple values from cache with the specified keys.
  132. * Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time,
  133. * which may improve the performance. In case a cache does not support this feature natively,
  134. * this method will try to simulate it.
  135. *
  136. * @param string[] $keys list of string keys identifying the cached values
  137. * @return array list of cached values corresponding to the specified keys. The array
  138. * is returned in terms of (key, value) pairs.
  139. * If a value is not cached or expired, the corresponding array value will be false.
  140. * @deprecated This method is an alias for [[multiGet()]] and will be removed in 2.1.0.
  141. */
  142. public function mget($keys)
  143. {
  144. return $this->multiGet($keys);
  145. }
  146. /**
  147. * Retrieves multiple values from cache with the specified keys.
  148. * Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time,
  149. * which may improve the performance. In case a cache does not support this feature natively,
  150. * this method will try to simulate it.
  151. * @param string[] $keys list of string keys identifying the cached values
  152. * @return array list of cached values corresponding to the specified keys. The array
  153. * is returned in terms of (key, value) pairs.
  154. * If a value is not cached or expired, the corresponding array value will be false.
  155. * @since 2.0.7
  156. */
  157. public function multiGet($keys)
  158. {
  159. $keyMap = [];
  160. foreach ($keys as $key) {
  161. $keyMap[$key] = $this->buildKey($key);
  162. }
  163. $values = $this->getValues(array_values($keyMap));
  164. $results = [];
  165. foreach ($keyMap as $key => $newKey) {
  166. $results[$key] = false;
  167. if (isset($values[$newKey])) {
  168. if ($this->serializer === false) {
  169. $results[$key] = $values[$newKey];
  170. } else {
  171. $value = $this->serializer === null ? unserialize($values[$newKey])
  172. : call_user_func($this->serializer[1], $values[$newKey]);
  173. if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->getHasChanged($this))) {
  174. $results[$key] = $value[0];
  175. }
  176. }
  177. }
  178. }
  179. return $results;
  180. }
  181. /**
  182. * Stores a value identified by a key into cache.
  183. * If the cache already contains such a key, the existing value and
  184. * expiration time will be replaced with the new ones, respectively.
  185. *
  186. * @param mixed $key a key identifying the value to be cached. This can be a simple string or
  187. * a complex data structure consisting of factors representing the key.
  188. * @param mixed $value the value to be cached
  189. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  190. * @param Dependency $dependency dependency of the cached item. If the dependency changes,
  191. * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
  192. * This parameter is ignored if [[serializer]] is false.
  193. * @return boolean whether the value is successfully stored into cache
  194. */
  195. public function set($key, $value, $duration = 0, $dependency = null)
  196. {
  197. if ($dependency !== null && $this->serializer !== false) {
  198. $dependency->evaluateDependency($this);
  199. }
  200. if ($this->serializer === null) {
  201. $value = serialize([$value, $dependency]);
  202. } elseif ($this->serializer !== false) {
  203. $value = call_user_func($this->serializer[0], [$value, $dependency]);
  204. }
  205. $key = $this->buildKey($key);
  206. return $this->setValue($key, $value, $duration);
  207. }
  208. /**
  209. * Stores multiple items in cache. Each item contains a value identified by a key.
  210. * If the cache already contains such a key, the existing value and
  211. * expiration time will be replaced with the new ones, respectively.
  212. *
  213. * @param array $items the items to be cached, as key-value pairs.
  214. * @param integer $duration default number of seconds in which the cached values will expire. 0 means never expire.
  215. * @param Dependency $dependency dependency of the cached items. If the dependency changes,
  216. * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
  217. * This parameter is ignored if [[serializer]] is false.
  218. * @return boolean whether the items are successfully stored into cache
  219. * @deprecated This method is an alias for [[multiSet()]] and will be removed in 2.1.0.
  220. */
  221. public function mset($items, $duration = 0, $dependency = null)
  222. {
  223. return $this->multiSet($items, $duration, $dependency);
  224. }
  225. /**
  226. * Stores multiple items in cache. Each item contains a value identified by a key.
  227. * If the cache already contains such a key, the existing value and
  228. * expiration time will be replaced with the new ones, respectively.
  229. *
  230. * @param array $items the items to be cached, as key-value pairs.
  231. * @param integer $duration default number of seconds in which the cached values will expire. 0 means never expire.
  232. * @param Dependency $dependency dependency of the cached items. If the dependency changes,
  233. * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
  234. * This parameter is ignored if [[serializer]] is false.
  235. * @return boolean whether the items are successfully stored into cache
  236. * @since 2.0.7
  237. */
  238. public function multiSet($items, $duration = 0, $dependency = null)
  239. {
  240. if ($dependency !== null && $this->serializer !== false) {
  241. $dependency->evaluateDependency($this);
  242. }
  243. $data = [];
  244. foreach ($items as $key => $value) {
  245. if ($this->serializer === null) {
  246. $value = serialize([$value, $dependency]);
  247. } elseif ($this->serializer !== false) {
  248. $value = call_user_func($this->serializer[0], [$value, $dependency]);
  249. }
  250. $key = $this->buildKey($key);
  251. $data[$key] = $value;
  252. }
  253. return $this->setValues($data, $duration);
  254. }
  255. /**
  256. * Stores multiple items in cache. Each item contains a value identified by a key.
  257. * If the cache already contains such a key, the existing value and expiration time will be preserved.
  258. *
  259. * @param array $items the items to be cached, as key-value pairs.
  260. * @param integer $duration default number of seconds in which the cached values will expire. 0 means never expire.
  261. * @param Dependency $dependency dependency of the cached items. If the dependency changes,
  262. * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
  263. * This parameter is ignored if [[serializer]] is false.
  264. * @return boolean whether the items are successfully stored into cache
  265. * @deprecated This method is an alias for [[multiAdd()]] and will be removed in 2.1.0.
  266. */
  267. public function madd($items, $duration = 0, $dependency = null)
  268. {
  269. return $this->multiAdd($items, $duration, $dependency);
  270. }
  271. /**
  272. * Stores multiple items in cache. Each item contains a value identified by a key.
  273. * If the cache already contains such a key, the existing value and expiration time will be preserved.
  274. *
  275. * @param array $items the items to be cached, as key-value pairs.
  276. * @param integer $duration default number of seconds in which the cached values will expire. 0 means never expire.
  277. * @param Dependency $dependency dependency of the cached items. If the dependency changes,
  278. * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
  279. * This parameter is ignored if [[serializer]] is false.
  280. * @return boolean whether the items are successfully stored into cache
  281. * @since 2.0.7
  282. */
  283. public function multiAdd($items, $duration = 0, $dependency = null)
  284. {
  285. if ($dependency !== null && $this->serializer !== false) {
  286. $dependency->evaluateDependency($this);
  287. }
  288. $data = [];
  289. foreach ($items as $key => $value) {
  290. if ($this->serializer === null) {
  291. $value = serialize([$value, $dependency]);
  292. } elseif ($this->serializer !== false) {
  293. $value = call_user_func($this->serializer[0], [$value, $dependency]);
  294. }
  295. $key = $this->buildKey($key);
  296. $data[$key] = $value;
  297. }
  298. return $this->addValues($data, $duration);
  299. }
  300. /**
  301. * Stores a value identified by a key into cache if the cache does not contain this key.
  302. * Nothing will be done if the cache already contains the key.
  303. * @param mixed $key a key identifying the value to be cached. This can be a simple string or
  304. * a complex data structure consisting of factors representing the key.
  305. * @param mixed $value the value to be cached
  306. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  307. * @param Dependency $dependency dependency of the cached item. If the dependency changes,
  308. * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
  309. * This parameter is ignored if [[serializer]] is false.
  310. * @return boolean whether the value is successfully stored into cache
  311. */
  312. public function add($key, $value, $duration = 0, $dependency = null)
  313. {
  314. if ($dependency !== null && $this->serializer !== false) {
  315. $dependency->evaluateDependency($this);
  316. }
  317. if ($this->serializer === null) {
  318. $value = serialize([$value, $dependency]);
  319. } elseif ($this->serializer !== false) {
  320. $value = call_user_func($this->serializer[0], [$value, $dependency]);
  321. }
  322. $key = $this->buildKey($key);
  323. return $this->addValue($key, $value, $duration);
  324. }
  325. /**
  326. * Deletes a value with the specified key from cache
  327. * @param mixed $key a key identifying the value to be deleted from cache. This can be a simple string or
  328. * a complex data structure consisting of factors representing the key.
  329. * @return boolean if no error happens during deletion
  330. */
  331. public function delete($key)
  332. {
  333. $key = $this->buildKey($key);
  334. return $this->deleteValue($key);
  335. }
  336. /**
  337. * Deletes all values from cache.
  338. * Be careful of performing this operation if the cache is shared among multiple applications.
  339. * @return boolean whether the flush operation was successful.
  340. */
  341. public function flush()
  342. {
  343. return $this->flushValues();
  344. }
  345. /**
  346. * Retrieves a value from cache with a specified key.
  347. * This method should be implemented by child classes to retrieve the data
  348. * from specific cache storage.
  349. * @param string $key a unique key identifying the cached value
  350. * @return mixed|false the value stored in cache, false if the value is not in the cache or expired. Most often
  351. * value is a string. If you have disabled [[serializer]], it could be something else.
  352. */
  353. abstract protected function getValue($key);
  354. /**
  355. * Stores a value identified by a key in cache.
  356. * This method should be implemented by child classes to store the data
  357. * in specific cache storage.
  358. * @param string $key the key identifying the value to be cached
  359. * @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
  360. * it could be something else.
  361. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  362. * @return boolean true if the value is successfully stored into cache, false otherwise
  363. */
  364. abstract protected function setValue($key, $value, $duration);
  365. /**
  366. * Stores a value identified by a key into cache if the cache does not contain this key.
  367. * This method should be implemented by child classes to store the data
  368. * in specific cache storage.
  369. * @param string $key the key identifying the value to be cached
  370. * @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
  371. * it could be something else.
  372. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  373. * @return boolean true if the value is successfully stored into cache, false otherwise
  374. */
  375. abstract protected function addValue($key, $value, $duration);
  376. /**
  377. * Deletes a value with the specified key from cache
  378. * This method should be implemented by child classes to delete the data from actual cache storage.
  379. * @param string $key the key of the value to be deleted
  380. * @return boolean if no error happens during deletion
  381. */
  382. abstract protected function deleteValue($key);
  383. /**
  384. * Deletes all values from cache.
  385. * Child classes may implement this method to realize the flush operation.
  386. * @return boolean whether the flush operation was successful.
  387. */
  388. abstract protected function flushValues();
  389. /**
  390. * Retrieves multiple values from cache with the specified keys.
  391. * The default implementation calls [[getValue()]] multiple times to retrieve
  392. * the cached values one by one. If the underlying cache storage supports multiget,
  393. * this method should be overridden to exploit that feature.
  394. * @param array $keys a list of keys identifying the cached values
  395. * @return array a list of cached values indexed by the keys
  396. */
  397. protected function getValues($keys)
  398. {
  399. $results = [];
  400. foreach ($keys as $key) {
  401. $results[$key] = $this->getValue($key);
  402. }
  403. return $results;
  404. }
  405. /**
  406. * Stores multiple key-value pairs in cache.
  407. * The default implementation calls [[setValue()]] multiple times store values one by one. If the underlying cache
  408. * storage supports multi-set, this method should be overridden to exploit that feature.
  409. * @param array $data array where key corresponds to cache key while value is the value stored
  410. * @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
  411. * @return array array of failed keys
  412. */
  413. protected function setValues($data, $duration)
  414. {
  415. $failedKeys = [];
  416. foreach ($data as $key => $value) {
  417. if ($this->setValue($key, $value, $duration) === false) {
  418. $failedKeys[] = $key;
  419. }
  420. }
  421. return $failedKeys;
  422. }
  423. /**
  424. * Adds multiple key-value pairs to cache.
  425. * The default implementation calls [[addValue()]] multiple times add values one by one. If the underlying cache
  426. * storage supports multi-add, this method should be overridden to exploit that feature.
  427. * @param array $data array where key corresponds to cache key while value is the value stored.
  428. * @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
  429. * @return array array of failed keys
  430. */
  431. protected function addValues($data, $duration)
  432. {
  433. $failedKeys = [];
  434. foreach ($data as $key => $value) {
  435. if ($this->addValue($key, $value, $duration) === false) {
  436. $failedKeys[] = $key;
  437. }
  438. }
  439. return $failedKeys;
  440. }
  441. /**
  442. * Returns whether there is a cache entry with a specified key.
  443. * This method is required by the interface [[\ArrayAccess]].
  444. * @param string $key a key identifying the cached value
  445. * @return boolean
  446. */
  447. public function offsetExists($key)
  448. {
  449. return $this->get($key) !== false;
  450. }
  451. /**
  452. * Retrieves the value from cache with a specified key.
  453. * This method is required by the interface [[\ArrayAccess]].
  454. * @param string $key a key identifying the cached value
  455. * @return mixed the value stored in cache, false if the value is not in the cache or expired.
  456. */
  457. public function offsetGet($key)
  458. {
  459. return $this->get($key);
  460. }
  461. /**
  462. * Stores the value identified by a key into cache.
  463. * If the cache already contains such a key, the existing value will be
  464. * replaced with the new ones. To add expiration and dependencies, use the [[set()]] method.
  465. * This method is required by the interface [[\ArrayAccess]].
  466. * @param string $key the key identifying the value to be cached
  467. * @param mixed $value the value to be cached
  468. */
  469. public function offsetSet($key, $value)
  470. {
  471. $this->set($key, $value);
  472. }
  473. /**
  474. * Deletes the value with the specified key from cache
  475. * This method is required by the interface [[\ArrayAccess]].
  476. * @param string $key the key of the value to be deleted
  477. */
  478. public function offsetUnset($key)
  479. {
  480. $this->delete($key);
  481. }
  482. }