Cache.php 25 KB

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