Yii原始碼分析之ArrayCache
阿新 • • 發佈:2018-12-28
ArrayCache僅通過將值儲存在陣列中來為當前請求提供快取。
有關ArrayCache支援的常見快取操作,請參閱yii \ caching \ Cache。
與yii \ caching \ Cache不同,ArrayCache允許set(),add(),multiSet()和multiAdd()的expire引數為浮點數,因此您可以指定以毫秒為單位的時間(例如,0.1將為100)毫秒)。
為了增強ArrayCache的效能,可以通過將$ serializer設定為false來禁用儲存資料的序列化。
我們看下其原始碼:
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\caching; /** * ArrayCache provides caching for the current request only by storing the values in an array. * * See [[Cache]] for common cache operations that ArrayCache supports. * * Unlike the [[Cache]], ArrayCache allows the expire parameter of [[set]], [[add]], [[multiSet]] and [[multiAdd]] to * be a floating point number, so you may specify the time in milliseconds (e.g. 0.1 will be 100 milliseconds). * * For enhanced performance of ArrayCache, you can disable serialization of the stored data by setting [[$serializer]] to `false`. * * For more details and usage information on Cache, see the [guide article on caching](guide:caching-overview). * * @author Carsten Brandt <
[email protected]> * @since 2.0 */ class ArrayCache extends Cache { private $_cache = []; /** * {@inheritdoc} */ public function exists($key) { $key = $this->buildKey($key); return isset($this->_cache[$key]) && ($this->_cache[$key][1] === 0 || $this->_cache[$key][1] > microtime(true)); } /** * {@inheritdoc} */ protected function getValue($key) { if (isset($this->_cache[$key]) && ($this->_cache[$key][1] === 0 || $this->_cache[$key][1] > microtime(true))) { return $this->_cache[$key][0]; } return false; } /** * {@inheritdoc} */ protected function setValue($key, $value, $duration) { $this->_cache[$key] = [$value, $duration === 0 ? 0 : microtime(true) + $duration]; return true; } /** * {@inheritdoc} */ protected function addValue($key, $value, $duration) { if (isset($this->_cache[$key]) && ($this->_cache[$key][1] === 0 || $this->_cache[$key][1] > microtime(true))) { return false; } $this->_cache[$key] = [$value, $duration === 0 ? 0 : microtime(true) + $duration]; return true; } /** * {@inheritdoc} */ protected function deleteValue($key) { unset($this->_cache[$key]); return true; } /** * {@inheritdoc} */ protected function flushValues() { $this->_cache = []; return true; } }