You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

524 lines
22KB

  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 array|boolean 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.
  66. */
  67. public $serializer;
  68. /**
  69. * Builds a normalized cache key from a given key.
  70. *
  71. * If the given key is a string containing alphanumeric characters only and no more than 32 characters,
  72. * then the key will be returned back prefixed with [[keyPrefix]]. Otherwise, a normalized key
  73. * is generated by serializing the given key, applying MD5 hashing, and prefixing with [[keyPrefix]].
  74. *
  75. * @param mixed $key the key to be normalized
  76. * @return string the generated cache key
  77. */
  78. public function buildKey($key)
  79. {
  80. if (is_string($key)) {
  81. $key = ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);
  82. } else {
  83. $key = md5(json_encode($key));
  84. }
  85. return $this->keyPrefix . $key;
  86. }
  87. /**
  88. * Retrieves a value from cache with a specified key.
  89. * @param mixed $key a key identifying the cached value. This can be a simple string or
  90. * a complex data structure consisting of factors representing the key.
  91. * @return mixed the value stored in cache, false if the value is not in the cache, expired,
  92. * or the dependency associated with the cached data has changed.
  93. */
  94. public function get($key)
  95. {
  96. $key = $this->buildKey($key);
  97. $value = $this->getValue($key);
  98. if ($value === false || $this->serializer === false) {
  99. return $value;
  100. } elseif ($this->serializer === null) {
  101. $value = unserialize($value);
  102. } else {
  103. $value = call_user_func($this->serializer[1], $value);
  104. }
  105. if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->getHasChanged($this))) {
  106. return $value[0];
  107. } else {
  108. return false;
  109. }
  110. }
  111. /**
  112. * Checks whether a specified key exists in the cache.
  113. * This can be faster than getting the value from the cache if the data is big.
  114. * In case a cache does not support this feature natively, this method will try to simulate it
  115. * but has no performance improvement over getting it.
  116. * Note that this method does not check whether the dependency associated
  117. * with the cached data, if there is any, has changed. So a call to [[get]]
  118. * may return false while exists returns true.
  119. * @param mixed $key a key identifying the cached value. This can be a simple string or
  120. * a complex data structure consisting of factors representing the key.
  121. * @return boolean true if a value exists in cache, false if the value is not in the cache or expired.
  122. */
  123. public function exists($key)
  124. {
  125. $key = $this->buildKey($key);
  126. $value = $this->getValue($key);
  127. return $value !== false;
  128. }
  129. /**
  130. * Retrieves multiple values from cache with the specified keys.
  131. * Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time,
  132. * which may improve the performance. In case a cache does not support this feature natively,
  133. * this method will try to simulate it.
  134. *
  135. * @param string[] $keys list of string keys identifying the cached values
  136. * @return array list of cached values corresponding to the specified keys. The array
  137. * is returned in terms of (key, value) pairs.
  138. * If a value is not cached or expired, the corresponding array value will be false.
  139. * @deprecated This method is an alias for [[multiGet()]] and will be removed in 2.1.0.
  140. */
  141. public function mget($keys)
  142. {
  143. return $this->multiGet($keys);
  144. }
  145. /**
  146. * Retrieves multiple values from cache with the specified keys.
  147. * Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time,
  148. * which may improve the performance. In case a cache does not support this feature natively,
  149. * this method will try to simulate it.
  150. * @param string[] $keys list of string keys identifying the cached values
  151. * @return array list of cached values corresponding to the specified keys. The array
  152. * is returned in terms of (key, value) pairs.
  153. * If a value is not cached or expired, the corresponding array value will be false.
  154. * @since 2.0.7
  155. */
  156. public function multiGet($keys)
  157. {
  158. $keyMap = [];
  159. foreach ($keys as $key) {
  160. $keyMap[$key] = $this->buildKey($key);
  161. }
  162. $values = $this->getValues(array_values($keyMap));
  163. $results = [];
  164. foreach ($keyMap as $key => $newKey) {
  165. $results[$key] = false;
  166. if (isset($values[$newKey])) {
  167. if ($this->serializer === false) {
  168. $results[$key] = $values[$newKey];
  169. } else {
  170. $value = $this->serializer === null ? unserialize($values[$newKey])
  171. : call_user_func($this->serializer[1], $values[$newKey]);
  172. if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->getHasChanged($this))) {
  173. $results[$key] = $value[0];
  174. }
  175. }
  176. }
  177. }
  178. return $results;
  179. }
  180. /**
  181. * Stores a value identified by a key into cache.
  182. * If the cache already contains such a key, the existing value and
  183. * expiration time will be replaced with the new ones, respectively.
  184. *
  185. * @param mixed $key a key identifying the value to be cached. This can be a simple string or
  186. * a complex data structure consisting of factors representing the key.
  187. * @param mixed $value the value to be cached
  188. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  189. * @param Dependency $dependency dependency of the cached item. If the dependency changes,
  190. * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
  191. * This parameter is ignored if [[serializer]] is false.
  192. * @return boolean whether the value is successfully stored into cache
  193. */
  194. public function set($key, $value, $duration = 0, $dependency = null)
  195. {
  196. if ($dependency !== null && $this->serializer !== false) {
  197. $dependency->evaluateDependency($this);
  198. }
  199. if ($this->serializer === null) {
  200. $value = serialize([$value, $dependency]);
  201. } elseif ($this->serializer !== false) {
  202. $value = call_user_func($this->serializer[0], [$value, $dependency]);
  203. }
  204. $key = $this->buildKey($key);
  205. return $this->setValue($key, $value, $duration);
  206. }
  207. /**
  208. * Stores multiple items in cache. Each item contains a value identified by a key.
  209. * If the cache already contains such a key, the existing value and
  210. * expiration time will be replaced with the new ones, respectively.
  211. *
  212. * @param array $items the items to be cached, as key-value pairs.
  213. * @param integer $duration default number of seconds in which the cached values will expire. 0 means never expire.
  214. * @param Dependency $dependency dependency of the cached items. If the dependency changes,
  215. * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
  216. * This parameter is ignored if [[serializer]] is false.
  217. * @return boolean whether the items are successfully stored into cache
  218. * @deprecated This method is an alias for [[multiSet()]] and will be removed in 2.1.0.
  219. */
  220. public function mset($items, $duration = 0, $dependency = null)
  221. {
  222. return $this->multiSet($items, $duration, $dependency);
  223. }
  224. /**
  225. * Stores multiple items in cache. Each item contains a value identified by a key.
  226. * If the cache already contains such a key, the existing value and
  227. * expiration time will be replaced with the new ones, respectively.
  228. *
  229. * @param array $items the items to be cached, as key-value pairs.
  230. * @param integer $duration default number of seconds in which the cached values will expire. 0 means never expire.
  231. * @param Dependency $dependency dependency of the cached items. If the dependency changes,
  232. * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
  233. * This parameter is ignored if [[serializer]] is false.
  234. * @return boolean whether the items are successfully stored into cache
  235. * @since 2.0.7
  236. */
  237. public function multiSet($items, $duration = 0, $dependency = null)
  238. {
  239. if ($dependency !== null && $this->serializer !== false) {
  240. $dependency->evaluateDependency($this);
  241. }
  242. $data = [];
  243. foreach ($items as $key => $value) {
  244. if ($this->serializer === null) {
  245. $value = serialize([$value, $dependency]);
  246. } elseif ($this->serializer !== false) {
  247. $value = call_user_func($this->serializer[0], [$value, $dependency]);
  248. }
  249. $key = $this->buildKey($key);
  250. $data[$key] = $value;
  251. }
  252. return $this->setValues($data, $duration);
  253. }
  254. /**
  255. * Stores multiple items in cache. Each item contains a value identified by a key.
  256. * If the cache already contains such a key, the existing value and expiration time will be preserved.
  257. *
  258. * @param array $items the items to be cached, as key-value pairs.
  259. * @param integer $duration default number of seconds in which the cached values will expire. 0 means never expire.
  260. * @param Dependency $dependency dependency of the cached items. If the dependency changes,
  261. * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
  262. * This parameter is ignored if [[serializer]] is false.
  263. * @return boolean whether the items are successfully stored into cache
  264. * @deprecated This method is an alias for [[multiAdd()]] and will be removed in 2.1.0.
  265. */
  266. public function madd($items, $duration = 0, $dependency = null)
  267. {
  268. return $this->multiAdd($items, $duration, $dependency);
  269. }
  270. /**
  271. * Stores multiple items in cache. Each item contains a value identified by a key.
  272. * If the cache already contains such a key, the existing value and expiration time will be preserved.
  273. *
  274. * @param array $items the items to be cached, as key-value pairs.
  275. * @param integer $duration default number of seconds in which the cached values will expire. 0 means never expire.
  276. * @param Dependency $dependency dependency of the cached items. If the dependency changes,
  277. * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
  278. * This parameter is ignored if [[serializer]] is false.
  279. * @return boolean whether the items are successfully stored into cache
  280. * @since 2.0.7
  281. */
  282. public function multiAdd($items, $duration = 0, $dependency = null)
  283. {
  284. if ($dependency !== null && $this->serializer !== false) {
  285. $dependency->evaluateDependency($this);
  286. }
  287. $data = [];
  288. foreach ($items as $key => $value) {
  289. if ($this->serializer === null) {
  290. $value = serialize([$value, $dependency]);
  291. } elseif ($this->serializer !== false) {
  292. $value = call_user_func($this->serializer[0], [$value, $dependency]);
  293. }
  294. $key = $this->buildKey($key);
  295. $data[$key] = $value;
  296. }
  297. return $this->addValues($data, $duration);
  298. }
  299. /**
  300. * Stores a value identified by a key into cache if the cache does not contain this key.
  301. * Nothing will be done if the cache already contains the key.
  302. * @param mixed $key a key identifying the value to be cached. This can be a simple string or
  303. * a complex data structure consisting of factors representing the key.
  304. * @param mixed $value the value to be cached
  305. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  306. * @param Dependency $dependency dependency of the cached item. If the dependency changes,
  307. * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
  308. * This parameter is ignored if [[serializer]] is false.
  309. * @return boolean whether the value is successfully stored into cache
  310. */
  311. public function add($key, $value, $duration = 0, $dependency = null)
  312. {
  313. if ($dependency !== null && $this->serializer !== false) {
  314. $dependency->evaluateDependency($this);
  315. }
  316. if ($this->serializer === null) {
  317. $value = serialize([$value, $dependency]);
  318. } elseif ($this->serializer !== false) {
  319. $value = call_user_func($this->serializer[0], [$value, $dependency]);
  320. }
  321. $key = $this->buildKey($key);
  322. return $this->addValue($key, $value, $duration);
  323. }
  324. /**
  325. * Deletes a value with the specified key from cache
  326. * @param mixed $key a key identifying the value to be deleted from cache. This can be a simple string or
  327. * a complex data structure consisting of factors representing the key.
  328. * @return boolean if no error happens during deletion
  329. */
  330. public function delete($key)
  331. {
  332. $key = $this->buildKey($key);
  333. return $this->deleteValue($key);
  334. }
  335. /**
  336. * Deletes all values from cache.
  337. * Be careful of performing this operation if the cache is shared among multiple applications.
  338. * @return boolean whether the flush operation was successful.
  339. */
  340. public function flush()
  341. {
  342. return $this->flushValues();
  343. }
  344. /**
  345. * Retrieves a value from cache with a specified key.
  346. * This method should be implemented by child classes to retrieve the data
  347. * from specific cache storage.
  348. * @param string $key a unique key identifying the cached value
  349. * @return string|boolean the value stored in cache, false if the value is not in the cache or expired.
  350. */
  351. abstract protected function getValue($key);
  352. /**
  353. * Stores a value identified by a key in cache.
  354. * This method should be implemented by child classes to store the data
  355. * in specific cache storage.
  356. * @param string $key the key identifying the value to be cached
  357. * @param string $value the value to be cached
  358. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  359. * @return boolean true if the value is successfully stored into cache, false otherwise
  360. */
  361. abstract protected function setValue($key, $value, $duration);
  362. /**
  363. * Stores a value identified by a key into cache if the cache does not contain this key.
  364. * This method should be implemented by child classes to store the data
  365. * in specific cache storage.
  366. * @param string $key the key identifying the value to be cached
  367. * @param string $value the value to be cached
  368. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  369. * @return boolean true if the value is successfully stored into cache, false otherwise
  370. */
  371. abstract protected function addValue($key, $value, $duration);
  372. /**
  373. * Deletes a value with the specified key from cache
  374. * This method should be implemented by child classes to delete the data from actual cache storage.
  375. * @param string $key the key of the value to be deleted
  376. * @return boolean if no error happens during deletion
  377. */
  378. abstract protected function deleteValue($key);
  379. /**
  380. * Deletes all values from cache.
  381. * Child classes may implement this method to realize the flush operation.
  382. * @return boolean whether the flush operation was successful.
  383. */
  384. abstract protected function flushValues();
  385. /**
  386. * Retrieves multiple values from cache with the specified keys.
  387. * The default implementation calls [[getValue()]] multiple times to retrieve
  388. * the cached values one by one. If the underlying cache storage supports multiget,
  389. * this method should be overridden to exploit that feature.
  390. * @param array $keys a list of keys identifying the cached values
  391. * @return array a list of cached values indexed by the keys
  392. */
  393. protected function getValues($keys)
  394. {
  395. $results = [];
  396. foreach ($keys as $key) {
  397. $results[$key] = $this->getValue($key);
  398. }
  399. return $results;
  400. }
  401. /**
  402. * Stores multiple key-value pairs in cache.
  403. * The default implementation calls [[setValue()]] multiple times store values one by one. If the underlying cache
  404. * storage supports multi-set, this method should be overridden to exploit that feature.
  405. * @param array $data array where key corresponds to cache key while value is the value stored
  406. * @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
  407. * @return array array of failed keys
  408. */
  409. protected function setValues($data, $duration)
  410. {
  411. $failedKeys = [];
  412. foreach ($data as $key => $value) {
  413. if ($this->setValue($key, $value, $duration) === false) {
  414. $failedKeys[] = $key;
  415. }
  416. }
  417. return $failedKeys;
  418. }
  419. /**
  420. * Adds multiple key-value pairs to cache.
  421. * The default implementation calls [[addValue()]] multiple times add values one by one. If the underlying cache
  422. * storage supports multi-add, this method should be overridden to exploit that feature.
  423. * @param array $data array where key corresponds to cache key while value is the value stored
  424. * @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
  425. * @return array array of failed keys
  426. */
  427. protected function addValues($data, $duration)
  428. {
  429. $failedKeys = [];
  430. foreach ($data as $key => $value) {
  431. if ($this->addValue($key, $value, $duration) === false) {
  432. $failedKeys[] = $key;
  433. }
  434. }
  435. return $failedKeys;
  436. }
  437. /**
  438. * Returns whether there is a cache entry with a specified key.
  439. * This method is required by the interface [[\ArrayAccess]].
  440. * @param string $key a key identifying the cached value
  441. * @return boolean
  442. */
  443. public function offsetExists($key)
  444. {
  445. return $this->get($key) !== false;
  446. }
  447. /**
  448. * Retrieves the value from cache with a specified key.
  449. * This method is required by the interface [[\ArrayAccess]].
  450. * @param string $key a key identifying the cached value
  451. * @return mixed the value stored in cache, false if the value is not in the cache or expired.
  452. */
  453. public function offsetGet($key)
  454. {
  455. return $this->get($key);
  456. }
  457. /**
  458. * Stores the value identified by a key into cache.
  459. * If the cache already contains such a key, the existing value will be
  460. * replaced with the new ones. To add expiration and dependencies, use the [[set()]] method.
  461. * This method is required by the interface [[\ArrayAccess]].
  462. * @param string $key the key identifying the value to be cached
  463. * @param mixed $value the value to be cached
  464. */
  465. public function offsetSet($key, $value)
  466. {
  467. $this->set($key, $value);
  468. }
  469. /**
  470. * Deletes the value with the specified key from cache
  471. * This method is required by the interface [[\ArrayAccess]].
  472. * @param string $key the key of the value to be deleted
  473. */
  474. public function offsetUnset($key)
  475. {
  476. $this->delete($key);
  477. }
  478. }