Cache.php 25 KB

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