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 \ArrayAccess
  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 integer 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. } else {
  118. return false;
  119. }
  120. }
  121. /**
  122. * Checks whether a specified key exists in the cache.
  123. * This can be faster than getting the value from the cache if the data is big.
  124. * In case a cache does not support this feature natively, this method will try to simulate it
  125. * but has no performance improvement over getting it.
  126. * Note that this method does not check whether the dependency associated
  127. * with the cached data, if there is any, has changed. So a call to [[get]]
  128. * may return false while exists returns true.
  129. * @param mixed $key a key identifying the cached value. This can be a simple string or
  130. * a complex data structure consisting of factors representing the key.
  131. * @return bool true if a value exists in cache, false if the value is not in the cache or expired.
  132. */
  133. public function exists($key)
  134. {
  135. $key = $this->buildKey($key);
  136. $value = $this->getValue($key);
  137. return $value !== false;
  138. }
  139. /**
  140. * Retrieves multiple values from cache with the specified keys.
  141. * Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time,
  142. * which may improve the performance. In case a cache does not support this feature natively,
  143. * this method will try to simulate it.
  144. *
  145. * @param string[] $keys list of string keys identifying the cached values
  146. * @return array list of cached values corresponding to the specified keys. The array
  147. * is returned in terms of (key, value) pairs.
  148. * If a value is not cached or expired, the corresponding array value will be false.
  149. * @deprecated This method is an alias for [[multiGet()]] and will be removed in 2.1.0.
  150. */
  151. public function mget($keys)
  152. {
  153. return $this->multiGet($keys);
  154. }
  155. /**
  156. * Retrieves multiple values from cache with the specified keys.
  157. * Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time,
  158. * which may improve the performance. In case a cache does not support this feature natively,
  159. * this method will try to simulate it.
  160. * @param string[] $keys list of string keys identifying the cached values
  161. * @return array list of cached values corresponding to the specified keys. The array
  162. * is returned in terms of (key, value) pairs.
  163. * If a value is not cached or expired, the corresponding array value will be false.
  164. * @since 2.0.7
  165. */
  166. public function multiGet($keys)
  167. {
  168. $keyMap = [];
  169. foreach ($keys as $key) {
  170. $keyMap[$key] = $this->buildKey($key);
  171. }
  172. $values = $this->getValues(array_values($keyMap));
  173. $results = [];
  174. foreach ($keyMap as $key => $newKey) {
  175. $results[$key] = false;
  176. if (isset($values[$newKey])) {
  177. if ($this->serializer === false) {
  178. $results[$key] = $values[$newKey];
  179. } else {
  180. $value = $this->serializer === null ? unserialize($values[$newKey])
  181. : call_user_func($this->serializer[1], $values[$newKey]);
  182. if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->isChanged($this))) {
  183. $results[$key] = $value[0];
  184. }
  185. }
  186. }
  187. }
  188. return $results;
  189. }
  190. /**
  191. * Stores a value identified by a key into cache.
  192. * If the cache already contains such a key, the existing value and
  193. * expiration time will be replaced with the new ones, respectively.
  194. *
  195. * @param mixed $key a key identifying the value to be cached. This can be a simple string or
  196. * a complex data structure consisting of factors representing the key.
  197. * @param mixed $value the value to be cached
  198. * @param int $duration default duration in seconds before the cache will expire. If not set,
  199. * default [[defaultDuration]] value is used.
  200. * @param Dependency $dependency dependency of the cached item. If the dependency changes,
  201. * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
  202. * This parameter is ignored if [[serializer]] is false.
  203. * @return bool whether the value is successfully stored into cache
  204. */
  205. public function set($key, $value, $duration = null, $dependency = null)
  206. {
  207. if ($duration === null) {
  208. $duration = $this->defaultDuration;
  209. }
  210. if ($dependency !== null && $this->serializer !== false) {
  211. $dependency->evaluateDependency($this);
  212. }
  213. if ($this->serializer === null) {
  214. $value = serialize([$value, $dependency]);
  215. } elseif ($this->serializer !== false) {
  216. $value = call_user_func($this->serializer[0], [$value, $dependency]);
  217. }
  218. $key = $this->buildKey($key);
  219. return $this->setValue($key, $value, $duration);
  220. }
  221. /**
  222. * Stores multiple items in cache. Each item contains a value identified by a key.
  223. * If the cache already contains such a key, the existing value and
  224. * expiration time will be replaced with the new ones, respectively.
  225. *
  226. * @param array $items the items to be cached, as key-value pairs.
  227. * @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
  228. * @param Dependency $dependency dependency of the cached items. If the dependency changes,
  229. * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
  230. * This parameter is ignored if [[serializer]] is false.
  231. * @return array array of failed keys
  232. * @deprecated This method is an alias for [[multiSet()]] and will be removed in 2.1.0.
  233. */
  234. public function mset($items, $duration = 0, $dependency = null)
  235. {
  236. return $this->multiSet($items, $duration, $dependency);
  237. }
  238. /**
  239. * Stores multiple items in cache. Each item contains a value identified by a key.
  240. * If the cache already contains such a key, the existing value and
  241. * expiration time will be replaced with the new ones, respectively.
  242. *
  243. * @param array $items the items to be cached, as key-value pairs.
  244. * @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
  245. * @param Dependency $dependency dependency of the cached items. If the dependency changes,
  246. * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
  247. * This parameter is ignored if [[serializer]] is false.
  248. * @return array array of failed keys
  249. * @since 2.0.7
  250. */
  251. public function multiSet($items, $duration = 0, $dependency = null)
  252. {
  253. if ($dependency !== null && $this->serializer !== false) {
  254. $dependency->evaluateDependency($this);
  255. }
  256. $data = [];
  257. foreach ($items as $key => $value) {
  258. if ($this->serializer === null) {
  259. $value = serialize([$value, $dependency]);
  260. } elseif ($this->serializer !== false) {
  261. $value = call_user_func($this->serializer[0], [$value, $dependency]);
  262. }
  263. $key = $this->buildKey($key);
  264. $data[$key] = $value;
  265. }
  266. return $this->setValues($data, $duration);
  267. }
  268. /**
  269. * Stores multiple items in cache. Each item contains a value identified by a key.
  270. * If the cache already contains such a key, the existing value and expiration time will be preserved.
  271. *
  272. * @param array $items the items to be cached, as key-value pairs.
  273. * @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
  274. * @param Dependency $dependency dependency of the cached items. If the dependency changes,
  275. * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
  276. * This parameter is ignored if [[serializer]] is false.
  277. * @return array array of failed keys
  278. * @deprecated This method is an alias for [[multiAdd()]] and will be removed in 2.1.0.
  279. */
  280. public function madd($items, $duration = 0, $dependency = null)
  281. {
  282. return $this->multiAdd($items, $duration, $dependency);
  283. }
  284. /**
  285. * Stores multiple items in cache. Each item contains a value identified by a key.
  286. * If the cache already contains such a key, the existing value and expiration time will be preserved.
  287. *
  288. * @param array $items the items to be cached, as key-value pairs.
  289. * @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
  290. * @param Dependency $dependency dependency of the cached items. If the dependency changes,
  291. * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
  292. * This parameter is ignored if [[serializer]] is false.
  293. * @return array array of failed keys
  294. * @since 2.0.7
  295. */
  296. public function multiAdd($items, $duration = 0, $dependency = null)
  297. {
  298. if ($dependency !== null && $this->serializer !== false) {
  299. $dependency->evaluateDependency($this);
  300. }
  301. $data = [];
  302. foreach ($items as $key => $value) {
  303. if ($this->serializer === null) {
  304. $value = serialize([$value, $dependency]);
  305. } elseif ($this->serializer !== false) {
  306. $value = call_user_func($this->serializer[0], [$value, $dependency]);
  307. }
  308. $key = $this->buildKey($key);
  309. $data[$key] = $value;
  310. }
  311. return $this->addValues($data, $duration);
  312. }
  313. /**
  314. * Stores a value identified by a key into cache if the cache does not contain this key.
  315. * Nothing will be done if the cache already contains the key.
  316. * @param mixed $key a key identifying the value to be cached. This can be a simple string or
  317. * a complex data structure consisting of factors representing the key.
  318. * @param mixed $value the value to be cached
  319. * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
  320. * @param Dependency $dependency dependency of the cached item. If the dependency changes,
  321. * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
  322. * This parameter is ignored if [[serializer]] is false.
  323. * @return bool whether the value is successfully stored into cache
  324. */
  325. public function add($key, $value, $duration = 0, $dependency = null)
  326. {
  327. if ($dependency !== null && $this->serializer !== false) {
  328. $dependency->evaluateDependency($this);
  329. }
  330. if ($this->serializer === null) {
  331. $value = serialize([$value, $dependency]);
  332. } elseif ($this->serializer !== false) {
  333. $value = call_user_func($this->serializer[0], [$value, $dependency]);
  334. }
  335. $key = $this->buildKey($key);
  336. return $this->addValue($key, $value, $duration);
  337. }
  338. /**
  339. * Deletes a value with the specified key from cache
  340. * @param mixed $key a key identifying the value to be deleted from cache. This can be a simple string or
  341. * a complex data structure consisting of factors representing the key.
  342. * @return bool if no error happens during deletion
  343. */
  344. public function delete($key)
  345. {
  346. $key = $this->buildKey($key);
  347. return $this->deleteValue($key);
  348. }
  349. /**
  350. * Deletes all values from cache.
  351. * Be careful of performing this operation if the cache is shared among multiple applications.
  352. * @return bool whether the flush operation was successful.
  353. */
  354. public function flush()
  355. {
  356. return $this->flushValues();
  357. }
  358. /**
  359. * Retrieves a value from cache with a specified key.
  360. * This method should be implemented by child classes to retrieve the data
  361. * from specific cache storage.
  362. * @param string $key a unique key identifying the cached value
  363. * @return mixed|false the value stored in cache, false if the value is not in the cache or expired. Most often
  364. * value is a string. If you have disabled [[serializer]], it could be something else.
  365. */
  366. abstract protected function getValue($key);
  367. /**
  368. * Stores a value identified by a key in cache.
  369. * This method should be implemented by child classes to store the data
  370. * in specific cache storage.
  371. * @param string $key the key identifying the value to be cached
  372. * @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
  373. * it could be something else.
  374. * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
  375. * @return bool true if the value is successfully stored into cache, false otherwise
  376. */
  377. abstract protected function setValue($key, $value, $duration);
  378. /**
  379. * Stores a value identified by a key into cache if the cache does not contain this key.
  380. * This method should be implemented by child classes to store the data
  381. * in specific cache storage.
  382. * @param string $key the key identifying the value to be cached
  383. * @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
  384. * it could be something else.
  385. * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
  386. * @return bool true if the value is successfully stored into cache, false otherwise
  387. */
  388. abstract protected function addValue($key, $value, $duration);
  389. /**
  390. * Deletes a value with the specified key from cache
  391. * This method should be implemented by child classes to delete the data from actual cache storage.
  392. * @param string $key the key of the value to be deleted
  393. * @return bool if no error happens during deletion
  394. */
  395. abstract protected function deleteValue($key);
  396. /**
  397. * Deletes all values from cache.
  398. * Child classes may implement this method to realize the flush operation.
  399. * @return bool whether the flush operation was successful.
  400. */
  401. abstract protected function flushValues();
  402. /**
  403. * Retrieves multiple values from cache with the specified keys.
  404. * The default implementation calls [[getValue()]] multiple times to retrieve
  405. * the cached values one by one. If the underlying cache storage supports multiget,
  406. * this method should be overridden to exploit that feature.
  407. * @param array $keys a list of keys identifying the cached values
  408. * @return array a list of cached values indexed by the keys
  409. */
  410. protected function getValues($keys)
  411. {
  412. $results = [];
  413. foreach ($keys as $key) {
  414. $results[$key] = $this->getValue($key);
  415. }
  416. return $results;
  417. }
  418. /**
  419. * Stores multiple key-value pairs in cache.
  420. * The default implementation calls [[setValue()]] multiple times store values one by one. If the underlying cache
  421. * storage supports multi-set, this method should be overridden to exploit that feature.
  422. * @param array $data array where key corresponds to cache key while value is the value stored
  423. * @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
  424. * @return array array of failed keys
  425. */
  426. protected function setValues($data, $duration)
  427. {
  428. $failedKeys = [];
  429. foreach ($data as $key => $value) {
  430. if ($this->setValue($key, $value, $duration) === false) {
  431. $failedKeys[] = $key;
  432. }
  433. }
  434. return $failedKeys;
  435. }
  436. /**
  437. * Adds multiple key-value pairs to cache.
  438. * The default implementation calls [[addValue()]] multiple times add values one by one. If the underlying cache
  439. * storage supports multi-add, this method should be overridden to exploit that feature.
  440. * @param array $data array where key corresponds to cache key while value is the value stored.
  441. * @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
  442. * @return array array of failed keys
  443. */
  444. protected function addValues($data, $duration)
  445. {
  446. $failedKeys = [];
  447. foreach ($data as $key => $value) {
  448. if ($this->addValue($key, $value, $duration) === false) {
  449. $failedKeys[] = $key;
  450. }
  451. }
  452. return $failedKeys;
  453. }
  454. /**
  455. * Returns whether there is a cache entry with a specified key.
  456. * This method is required by the interface [[\ArrayAccess]].
  457. * @param string $key a key identifying the cached value
  458. * @return bool
  459. */
  460. public function offsetExists($key)
  461. {
  462. return $this->get($key) !== false;
  463. }
  464. /**
  465. * Retrieves the value from cache with a specified key.
  466. * This method is required by the interface [[\ArrayAccess]].
  467. * @param string $key a key identifying the cached value
  468. * @return mixed the value stored in cache, false if the value is not in the cache or expired.
  469. */
  470. public function offsetGet($key)
  471. {
  472. return $this->get($key);
  473. }
  474. /**
  475. * Stores the value identified by a key into cache.
  476. * If the cache already contains such a key, the existing value will be
  477. * replaced with the new ones. To add expiration and dependencies, use the [[set()]] method.
  478. * This method is required by the interface [[\ArrayAccess]].
  479. * @param string $key the key identifying the value to be cached
  480. * @param mixed $value the value to be cached
  481. */
  482. public function offsetSet($key, $value)
  483. {
  484. $this->set($key, $value);
  485. }
  486. /**
  487. * Deletes the value with the specified key from cache
  488. * This method is required by the interface [[\ArrayAccess]].
  489. * @param string $key the key of the value to be deleted
  490. */
  491. public function offsetUnset($key)
  492. {
  493. $this->delete($key);
  494. }
  495. /**
  496. * Method combines both [[set()]] and [[get()]] methods to retrieve value identified by a $key,
  497. * or to store the result of $callable execution if there is no cache available for the $key.
  498. *
  499. * Usage example:
  500. *
  501. * ```php
  502. * public function getTopProducts($count = 10) {
  503. * $cache = $this->cache; // Could be Yii::$app->cache
  504. * return $cache->getOrSet(['top-n-products', 'n' => $count], function ($cache) use ($count) {
  505. * return Products::find()->mostPopular()->limit(10)->all();
  506. * }, 1000);
  507. * }
  508. * ```
  509. *
  510. * @param mixed $key a key identifying the value to be cached. This can be a simple string or
  511. * a complex data structure consisting of factors representing the key.
  512. * @param callable|\Closure $callable the callable or closure that will be used to generate a value to be cached.
  513. * In case $callable returns `false`, the value will not be cached.
  514. * @param int $duration default duration in seconds before the cache will expire. If not set,
  515. * [[defaultDuration]] value will be used.
  516. * @param Dependency $dependency dependency of the cached item. If the dependency changes,
  517. * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
  518. * This parameter is ignored if [[serializer]] is `false`.
  519. * @return mixed result of $callable execution
  520. * @since 2.0.11
  521. */
  522. public function getOrSet($key, $callable, $duration = null, $dependency = null)
  523. {
  524. if (($value = $this->get($key)) !== false) {
  525. return $value;
  526. }
  527. $value = call_user_func($callable, $this);
  528. if (!$this->set($key, $value, $duration, $dependency)) {
  529. Yii::warning('Failed to set cache value for key ' . json_encode($key), __METHOD__);
  530. }
  531. return $value;
  532. }
  533. }