Fixes #14081: Added yii\caching\CacheInterface to make custom cache extensions adoption easier

This commit is contained in:
SilverFire - Dmitry Naumenko
2017-05-01 16:18:18 +03:00
committed by Alexander Makarov
parent 2b7e8be1e8
commit cb53b2feec
22 changed files with 249 additions and 61 deletions

View File

@ -11,6 +11,7 @@ Yii Framework 2 Change Log
- Enh #14089: Added tests for `yii\base\Theme` (vladis84) - Enh #14089: Added tests for `yii\base\Theme` (vladis84)
- Enh #13586: Added `$preserveNonEmptyValues` property to the `yii\behaviors\AttributeBehavior` (Kolyunya) - Enh #13586: Added `$preserveNonEmptyValues` property to the `yii\behaviors\AttributeBehavior` (Kolyunya)
- Bug #14192: Fixed wrong default null value for TIMESTAMP when using PostgreSQL (Tigrov) - Bug #14192: Fixed wrong default null value for TIMESTAMP when using PostgreSQL (Tigrov)
- Enh #14081: Added `yii\caching\CacheInterface` to make custom cache extensions adoption easier (silverfire)
2.0.12 June 05, 2017 2.0.12 June 05, 2017
-------------------- --------------------

View File

@ -19,7 +19,7 @@ use Yii;
* @property \yii\rbac\ManagerInterface $authManager The auth manager application component. Null is returned * @property \yii\rbac\ManagerInterface $authManager The auth manager application component. Null is returned
* if auth manager is not configured. This property is read-only. * if auth manager is not configured. This property is read-only.
* @property string $basePath The root directory of the application. * @property string $basePath The root directory of the application.
* @property \yii\caching\Cache $cache The cache application component. Null if the component is not enabled. * @property \yii\caching\CacheInterface $cache The cache application component. Null if the component is not enabled.
* This property is read-only. * This property is read-only.
* @property array $container Values given in terms of name-value pairs. This property is write-only. * @property array $container Values given in terms of name-value pairs. This property is write-only.
* @property \yii\db\Connection $db The database connection. This property is read-only. * @property \yii\db\Connection $db The database connection. This property is read-only.
@ -516,7 +516,7 @@ abstract class Application extends Module
/** /**
* Returns the cache component. * Returns the cache component.
* @return \yii\caching\Cache the cache application component. Null if the component is not enabled. * @return \yii\caching\CacheInterface the cache application component. Null if the component is not enabled.
*/ */
public function getCache() public function getCache()
{ {

View File

@ -51,7 +51,7 @@ use yii\helpers\StringHelper;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
abstract class Cache extends Component implements \ArrayAccess abstract class Cache extends Component implements CacheInterface
{ {
/** /**
* @var string a string prefixed to every cache key so that it is unique globally in the whole cache storage. * @var string a string prefixed to every cache key so that it is unique globally in the whole cache storage.

View File

@ -0,0 +1,187 @@
<?php
namespace yii\caching;
/**
* CacheInterface is the base interface for cache.
*
* A data item can be stored in the cache by calling [[set()]] and be retrieved back
* later (in the same or different request) by [[get()]]. In both operations,
* a key identifying the data item is required. An expiration time and/or a [[Dependency|dependency]]
* can also be specified when calling [[set()]]. If the data item expires or the dependency
* changes at the time of calling [[get()]], the cache will return no data.
*
* A typical usage pattern of cache is like the following:
*
* ```php
* $key = 'demo';
* $data = $cache->get($key);
* if ($data === false) {
* // ...generate $data here...
* $cache->set($key, $data, $duration, $dependency);
* }
* ```
*
* Because CacheInterface extends the [[\ArrayAccess]] interface, it can be used like an array. For example,
*
* ```php
* $cache['foo'] = 'some data';
* echo $cache['foo'];
* ```
*
* For more details and usage information on Cache, see the [guide article on caching](guide:caching-overview).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Dmitry Naumenko <d.naumenko.a@gmail.com>
* @since 2.0.13. Previous framework versions used abstract class [[yii\caching\Cache]] as interface.
*/
interface CacheInterface extends \ArrayAccess
{
/**
* Builds a normalized cache key from a given key.
*
* If the given key is a string containing alphanumeric characters only and no more than 32 characters,
* then the key will be returned back prefixed with [[keyPrefix]]. Otherwise, a normalized key
* is generated by serializing the given key, applying MD5 hashing, and prefixing with [[keyPrefix]].
*
* @param mixed $key the key to be normalized
* @return string the generated cache key
*/
public function buildKey($key);
/**
* Retrieves a value from cache with a specified key.
* @param mixed $key a key identifying the cached value. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @return mixed the value stored in cache, false if the value is not in the cache, expired,
* or the dependency associated with the cached data has changed.
*/
public function get($key);
/**
* Checks whether a specified key exists in the cache.
* This can be faster than getting the value from the cache if the data is big.
* In case a cache does not support this feature natively, this method will try to simulate it
* but has no performance improvement over getting it.
* Note that this method does not check whether the dependency associated
* with the cached data, if there is any, has changed. So a call to [[get]]
* may return false while exists returns true.
* @param mixed $key a key identifying the cached value. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @return bool true if a value exists in cache, false if the value is not in the cache or expired.
*/
public function exists($key);
/**
* Retrieves multiple values from cache with the specified keys.
* Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time,
* which may improve the performance. In case a cache does not support this feature natively,
* this method will try to simulate it.
* @param string[] $keys list of string keys identifying the cached values
* @return array list of cached values corresponding to the specified keys. The array
* is returned in terms of (key, value) pairs.
* If a value is not cached or expired, the corresponding array value will be false.
*/
public function multiGet($keys);
/**
* Stores a value identified by a key into cache.
* If the cache already contains such a key, the existing value and
* expiration time will be replaced with the new ones, respectively.
*
* @param mixed $key a key identifying the value to be cached. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @param mixed $value the value to be cached
* @param int $duration default duration in seconds before the cache will expire. If not set,
* default [[defaultDuration]] value is used.
* @param Dependency $dependency dependency of the cached item. If the dependency changes,
* the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
* This parameter is ignored if [[serializer]] is false.
* @return bool whether the value is successfully stored into cache
*/
public function set($key, $value, $duration = null, $dependency = null);
/**
* Stores multiple items in cache. Each item contains a value identified by a key.
* If the cache already contains such a key, the existing value and
* expiration time will be replaced with the new ones, respectively.
*
* @param array $items the items to be cached, as key-value pairs.
* @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
* @param Dependency $dependency dependency of the cached items. If the dependency changes,
* the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
* This parameter is ignored if [[serializer]] is false.
* @return array array of failed keys
*/
public function multiSet($items, $duration = 0, $dependency = null);
/**
* Stores a value identified by a key into cache if the cache does not contain this key.
* Nothing will be done if the cache already contains the key.
* @param mixed $key a key identifying the value to be cached. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @param mixed $value the value to be cached
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
* @param Dependency $dependency dependency of the cached item. If the dependency changes,
* the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
* This parameter is ignored if [[serializer]] is false.
* @return bool whether the value is successfully stored into cache
*/
public function add($key, $value, $duration = 0, $dependency = null);
/**
* Stores multiple items in cache. Each item contains a value identified by a key.
* If the cache already contains such a key, the existing value and expiration time will be preserved.
*
* @param array $items the items to be cached, as key-value pairs.
* @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
* @param Dependency $dependency dependency of the cached items. If the dependency changes,
* the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
* This parameter is ignored if [[serializer]] is false.
* @return array array of failed keys
*/
public function multiAdd($items, $duration = 0, $dependency = null);
/**
* Deletes a value with the specified key from cache
* @param mixed $key a key identifying the value to be deleted from cache. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @return bool if no error happens during deletion
*/
public function delete($key);
/**
* Deletes all values from cache.
* Be careful of performing this operation if the cache is shared among multiple applications.
* @return bool whether the flush operation was successful.
*/
public function flush();
/**
* Method combines both [[set()]] and [[get()]] methods to retrieve value identified by a $key,
* or to store the result of $callable execution if there is no cache available for the $key.
*
* Usage example:
*
* ```php
* public function getTopProducts($count = 10) {
* $cache = $this->cache; // Could be Yii::$app->cache
* return $cache->getOrSet(['top-n-products', 'n' => $count], function ($cache) use ($count) {
* return Products::find()->mostPopular()->limit(10)->all();
* }, 1000);
* }
* ```
*
* @param mixed $key a key identifying the value to be cached. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @param callable|\Closure $callable the callable or closure that will be used to generate a value to be cached.
* In case $callable returns `false`, the value will not be cached.
* @param int $duration default duration in seconds before the cache will expire. If not set,
* [[defaultDuration]] value will be used.
* @param Dependency $dependency dependency of the cached item. If the dependency changes,
* the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
* This parameter is ignored if [[serializer]] is `false`.
* @return mixed result of $callable execution
*/
public function getOrSet($key, $callable, $duration = null, $dependency = null);
}

View File

@ -37,7 +37,7 @@ class ChainedDependency extends Dependency
/** /**
* Evaluates the dependency by generating and saving the data related with dependency. * Evaluates the dependency by generating and saving the data related with dependency.
* @param Cache $cache the cache component that is currently evaluating this dependency * @param CacheInterface $cache the cache component that is currently evaluating this dependency
*/ */
public function evaluateDependency($cache) public function evaluateDependency($cache)
{ {
@ -49,7 +49,7 @@ class ChainedDependency extends Dependency
/** /**
* Generates the data needed to determine if dependency has been changed. * Generates the data needed to determine if dependency has been changed.
* This method does nothing in this class. * This method does nothing in this class.
* @param Cache $cache the cache component that is currently evaluating this dependency * @param CacheInterface $cache the cache component that is currently evaluating this dependency
* @return mixed the data needed to determine if dependency has been changed. * @return mixed the data needed to determine if dependency has been changed.
*/ */
protected function generateDependencyData($cache) protected function generateDependencyData($cache)

View File

@ -43,7 +43,7 @@ class DbDependency extends Dependency
/** /**
* Generates the data needed to determine if dependency has been changed. * Generates the data needed to determine if dependency has been changed.
* This method returns the value of the global state. * This method returns the value of the global state.
* @param Cache $cache the cache component that is currently evaluating this dependency * @param CacheInterface $cache the cache component that is currently evaluating this dependency
* @return mixed the data needed to determine if dependency has been changed. * @return mixed the data needed to determine if dependency has been changed.
* @throws InvalidConfigException if [[db]] is not a valid application component ID * @throws InvalidConfigException if [[db]] is not a valid application component ID
*/ */

View File

@ -62,7 +62,7 @@ class DbQueryDependency extends Dependency
/** /**
* Generates the data needed to determine if dependency is changed. * Generates the data needed to determine if dependency is changed.
* This method returns the query result * This method returns the query result
* @param Cache $cache the cache component that is currently evaluating this dependency * @param CacheInterface $cache the cache component that is currently evaluating this dependency
* @return mixed the data needed to determine if dependency has been changed. * @return mixed the data needed to determine if dependency has been changed.
* @throws InvalidConfigException on invalid configuration. * @throws InvalidConfigException on invalid configuration.
*/ */

View File

@ -42,7 +42,7 @@ abstract class Dependency extends \yii\base\Object
/** /**
* Evaluates the dependency by generating and saving the data related with dependency. * Evaluates the dependency by generating and saving the data related with dependency.
* This method is invoked by cache before writing data into it. * This method is invoked by cache before writing data into it.
* @param Cache $cache the cache component that is currently evaluating this dependency * @param CacheInterface $cache the cache component that is currently evaluating this dependency
*/ */
public function evaluateDependency($cache) public function evaluateDependency($cache)
{ {
@ -68,7 +68,7 @@ abstract class Dependency extends \yii\base\Object
/** /**
* Checks whether the dependency is changed * Checks whether the dependency is changed
* @param Cache $cache the cache component that is currently evaluating this dependency * @param CacheInterface $cache the cache component that is currently evaluating this dependency
* @return bool whether the dependency has changed. * @return bool whether the dependency has changed.
* @since 2.0.11 * @since 2.0.11
*/ */
@ -111,7 +111,7 @@ abstract class Dependency extends \yii\base\Object
/** /**
* Generates the data needed to determine if dependency is changed. * Generates the data needed to determine if dependency is changed.
* Derived classes should override this method to generate the actual dependency data. * Derived classes should override this method to generate the actual dependency data.
* @param Cache $cache the cache component that is currently evaluating this dependency * @param CacheInterface $cache the cache component that is currently evaluating this dependency
* @return mixed the data needed to determine if dependency has been changed. * @return mixed the data needed to determine if dependency has been changed.
*/ */
abstract protected function generateDependencyData($cache); abstract protected function generateDependencyData($cache);

View File

@ -40,7 +40,7 @@ class ExpressionDependency extends Dependency
/** /**
* Generates the data needed to determine if dependency has been changed. * Generates the data needed to determine if dependency has been changed.
* This method returns the result of the PHP expression. * This method returns the result of the PHP expression.
* @param Cache $cache the cache component that is currently evaluating this dependency * @param CacheInterface $cache the cache component that is currently evaluating this dependency
* @return mixed the data needed to determine if dependency has been changed. * @return mixed the data needed to determine if dependency has been changed.
*/ */
protected function generateDependencyData($cache) protected function generateDependencyData($cache)

View File

@ -33,7 +33,7 @@ class FileDependency extends Dependency
/** /**
* Generates the data needed to determine if dependency has been changed. * Generates the data needed to determine if dependency has been changed.
* This method returns the file's last modification time. * This method returns the file's last modification time.
* @param Cache $cache the cache component that is currently evaluating this dependency * @param CacheInterface $cache the cache component that is currently evaluating this dependency
* @return mixed the data needed to determine if dependency has been changed. * @return mixed the data needed to determine if dependency has been changed.
* @throws InvalidConfigException if [[fileName]] is not set * @throws InvalidConfigException if [[fileName]] is not set
*/ */

View File

@ -37,7 +37,7 @@ class TagDependency extends Dependency
/** /**
* Generates the data needed to determine if dependency has been changed. * Generates the data needed to determine if dependency has been changed.
* This method does nothing in this class. * This method does nothing in this class.
* @param Cache $cache the cache component that is currently evaluating this dependency * @param CacheInterface $cache the cache component that is currently evaluating this dependency
* @return mixed the data needed to determine if dependency has been changed. * @return mixed the data needed to determine if dependency has been changed.
*/ */
protected function generateDependencyData($cache) protected function generateDependencyData($cache)
@ -68,7 +68,7 @@ class TagDependency extends Dependency
/** /**
* Invalidates all of the cached data items that are associated with any of the specified [[tags]]. * Invalidates all of the cached data items that are associated with any of the specified [[tags]].
* @param Cache $cache the cache component that caches the data items * @param CacheInterface $cache the cache component that caches the data items
* @param string|array $tags * @param string|array $tags
*/ */
public static function invalidate($cache, $tags) public static function invalidate($cache, $tags)
@ -82,7 +82,7 @@ class TagDependency extends Dependency
/** /**
* Generates the timestamp for the specified cache keys. * Generates the timestamp for the specified cache keys.
* @param Cache $cache * @param CacheInterface $cache
* @param string[] $keys * @param string[] $keys
* @return array the timestamp indexed by cache keys * @return array the timestamp indexed by cache keys
*/ */
@ -99,7 +99,7 @@ class TagDependency extends Dependency
/** /**
* Returns the timestamps for the specified tags. * Returns the timestamps for the specified tags.
* @param Cache $cache * @param CacheInterface $cache
* @param string[] $tags * @param string[] $tags
* @return array the timestamps indexed by the specified tags. * @return array the timestamps indexed by the specified tags.
*/ */

View File

@ -9,8 +9,8 @@ namespace yii\console\controllers;
use Yii; use Yii;
use yii\caching\ApcCache; use yii\caching\ApcCache;
use yii\caching\CacheInterface;
use yii\console\Controller; use yii\console\Controller;
use yii\caching\Cache;
use yii\helpers\Console; use yii\helpers\Console;
use yii\console\Exception; use yii\console\Exception;
@ -265,7 +265,7 @@ class CacheController extends Controller
continue; continue;
} }
if ($component instanceof Cache) { if ($component instanceof CacheInterface) {
$caches[$name] = get_class($component); $caches[$name] = get_class($component);
} elseif (is_array($component) && isset($component['class']) && $this->isCacheClass($component['class'])) { } elseif (is_array($component) && isset($component['class']) && $this->isCacheClass($component['class'])) {
$caches[$name] = $component['class']; $caches[$name] = $component['class'];
@ -284,7 +284,7 @@ class CacheController extends Controller
*/ */
private function isCacheClass($className) private function isCacheClass($className)
{ {
return is_subclass_of($className, Cache::className()); return is_subclass_of($className, 'yii\caching\CacheInterface');
} }
/** /**

View File

@ -903,7 +903,7 @@ class Command extends Component
if ($method !== '') { if ($method !== '') {
$info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency); $info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency);
if (is_array($info)) { if (is_array($info)) {
/* @var $cache \yii\caching\Cache */ /* @var $cache \yii\caching\CacheInterface */
$cache = $info[0]; $cache = $info[0];
$cacheKey = [ $cacheKey = [
__CLASS__, __CLASS__,

View File

@ -12,7 +12,7 @@ use Yii;
use yii\base\Component; use yii\base\Component;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
use yii\base\NotSupportedException; use yii\base\NotSupportedException;
use yii\caching\Cache; use yii\caching\CacheInterface;
/** /**
* Connection represents a connection to a database via [PDO](http://php.net/manual/en/book.pdo.php). * Connection represents a connection to a database via [PDO](http://php.net/manual/en/book.pdo.php).
@ -207,7 +207,7 @@ class Connection extends Component
*/ */
public $schemaCacheExclude = []; public $schemaCacheExclude = [];
/** /**
* @var Cache|string the cache object or the ID of the cache application component that * @var CacheInterface|string the cache object or the ID of the cache application component that
* is used to cache the table metadata. * is used to cache the table metadata.
* @see enableSchemaCache * @see enableSchemaCache
*/ */
@ -231,7 +231,7 @@ class Connection extends Component
*/ */
public $queryCacheDuration = 3600; public $queryCacheDuration = 3600;
/** /**
* @var Cache|string the cache object or the ID of the cache application component * @var CacheInterface|string the cache object or the ID of the cache application component
* that is used for query caching. * that is used for query caching.
* @see enableQueryCache * @see enableQueryCache
*/ */
@ -302,7 +302,7 @@ class Connection extends Component
*/ */
public $enableSavepoint = true; public $enableSavepoint = true;
/** /**
* @var Cache|string the cache object or the ID of the cache application component that is used to store * @var CacheInterface|string the cache object or the ID of the cache application component that is used to store
* the health status of the DB servers specified in [[masters]] and [[slaves]]. * the health status of the DB servers specified in [[masters]] and [[slaves]].
* This is used only when read/write splitting is enabled or [[masters]] is not empty. * This is used only when read/write splitting is enabled or [[masters]] is not empty.
*/ */
@ -540,7 +540,7 @@ class Connection extends Component
} else { } else {
$cache = $this->queryCache; $cache = $this->queryCache;
} }
if ($cache instanceof Cache) { if ($cache instanceof CacheInterface) {
return [$cache, $duration, $dependency]; return [$cache, $duration, $dependency];
} }
} }
@ -1049,7 +1049,7 @@ class Connection extends Component
} }
$key = [__METHOD__, $config['dsn']]; $key = [__METHOD__, $config['dsn']];
if ($cache instanceof Cache && $cache->get($key)) { if ($cache instanceof CacheInterface && $cache->get($key)) {
// should not try this dead server now // should not try this dead server now
continue; continue;
} }
@ -1062,7 +1062,7 @@ class Connection extends Component
return $db; return $db;
} catch (\Exception $e) { } catch (\Exception $e) {
Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__); Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
if ($cache instanceof Cache) { if ($cache instanceof CacheInterface) {
// mark this server as dead and only retry it after the specified interval // mark this server as dead and only retry it after the specified interval
$cache->set($key, 1, $this->serverRetryInterval); $cache->set($key, 1, $this->serverRetryInterval);
} }

View File

@ -11,7 +11,7 @@ use Yii;
use yii\base\Object; use yii\base\Object;
use yii\base\NotSupportedException; use yii\base\NotSupportedException;
use yii\base\InvalidCallException; use yii\base\InvalidCallException;
use yii\caching\Cache; use yii\caching\CacheInterface;
use yii\caching\TagDependency; use yii\caching\TagDependency;
/** /**
@ -130,9 +130,9 @@ abstract class Schema extends Object
$realName = $this->getRawTableName($name); $realName = $this->getRawTableName($name);
if ($db->enableSchemaCache && !in_array($name, $db->schemaCacheExclude, true)) { if ($db->enableSchemaCache && !in_array($name, $db->schemaCacheExclude, true)) {
/* @var $cache Cache */ /* @var $cache CacheInterface */
$cache = is_string($db->schemaCache) ? Yii::$app->get($db->schemaCache, false) : $db->schemaCache; $cache = is_string($db->schemaCache) ? Yii::$app->get($db->schemaCache, false) : $db->schemaCache;
if ($cache instanceof Cache) { if ($cache instanceof CacheInterface) {
$key = $this->getCacheKey($name); $key = $this->getCacheKey($name);
if ($refresh || ($table = $cache->get($key)) === false) { if ($refresh || ($table = $cache->get($key)) === false) {
$this->_tables[$name] = $table = $this->loadTableSchema($realName); $this->_tables[$name] = $table = $this->loadTableSchema($realName);
@ -277,9 +277,9 @@ abstract class Schema extends Object
*/ */
public function refresh() public function refresh()
{ {
/* @var $cache Cache */ /* @var $cache CacheInterface */
$cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache; $cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
if ($this->db->enableSchemaCache && $cache instanceof Cache) { if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) {
TagDependency::invalidate($cache, $this->getCacheTag()); TagDependency::invalidate($cache, $this->getCacheTag());
} }
$this->_tableNames = []; $this->_tableNames = [];
@ -297,9 +297,9 @@ abstract class Schema extends Object
{ {
unset($this->_tables[$name]); unset($this->_tables[$name]);
$this->_tableNames = []; $this->_tableNames = [];
/* @var $cache Cache */ /* @var $cache CacheInterface */
$cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache; $cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
if ($this->db->enableSchemaCache && $cache instanceof Cache) { if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) {
$cache->delete($this->getCacheKey($name)); $cache->delete($this->getCacheKey($name));
} }
} }

View File

@ -10,7 +10,7 @@ namespace yii\filters;
use Yii; use Yii;
use yii\base\Action; use yii\base\Action;
use yii\base\ActionFilter; use yii\base\ActionFilter;
use yii\caching\Cache; use yii\caching\CacheInterface;
use yii\caching\Dependency; use yii\caching\Dependency;
use yii\di\Instance; use yii\di\Instance;
use yii\web\Response; use yii\web\Response;
@ -57,7 +57,7 @@ class PageCache extends ActionFilter
*/ */
public $varyByRoute = true; public $varyByRoute = true;
/** /**
* @var Cache|array|string the cache object or the application component ID of the cache object. * @var CacheInterface|array|string the cache object or the application component ID of the cache object.
* After the PageCache object is created, if you want to change this property, * After the PageCache object is created, if you want to change this property,
* you should only assign it with a cache object. * you should only assign it with a cache object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
@ -156,7 +156,7 @@ class PageCache extends ActionFilter
return true; return true;
} }
$this->cache = Instance::ensure($this->cache, Cache::className()); $this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface');
if (is_array($this->dependency)) { if (is_array($this->dependency)) {
$this->dependency = Yii::createObject($this->dependency); $this->dependency = Yii::createObject($this->dependency);

View File

@ -9,10 +9,10 @@ namespace yii\i18n;
use Yii; use Yii;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
use yii\caching\CacheInterface;
use yii\db\Expression; use yii\db\Expression;
use yii\di\Instance; use yii\di\Instance;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use yii\caching\Cache;
use yii\db\Connection; use yii\db\Connection;
use yii\db\Query; use yii\db\Query;
@ -55,7 +55,7 @@ class DbMessageSource extends MessageSource
*/ */
public $db = 'db'; public $db = 'db';
/** /**
* @var Cache|array|string the cache object or the application component ID of the cache object. * @var CacheInterface|array|string the cache object or the application component ID of the cache object.
* The messages data will be cached using this cache object. * The messages data will be cached using this cache object.
* Note, that to enable caching you have to set [[enableCaching]] to `true`, otherwise setting this property has no effect. * Note, that to enable caching you have to set [[enableCaching]] to `true`, otherwise setting this property has no effect.
* *
@ -98,7 +98,7 @@ class DbMessageSource extends MessageSource
parent::init(); parent::init();
$this->db = Instance::ensure($this->db, Connection::className()); $this->db = Instance::ensure($this->db, Connection::className());
if ($this->enableCaching) { if ($this->enableCaching) {
$this->cache = Instance::ensure($this->cache, Cache::className()); $this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface');
} }
} }

View File

@ -8,7 +8,7 @@
namespace yii\rbac; namespace yii\rbac;
use Yii; use Yii;
use yii\caching\Cache; use yii\caching\CacheInterface;
use yii\db\Connection; use yii\db\Connection;
use yii\db\Query; use yii\db\Query;
use yii\db\Expression; use yii\db\Expression;
@ -62,7 +62,7 @@ class DbManager extends BaseManager
*/ */
public $ruleTable = '{{%auth_rule}}'; public $ruleTable = '{{%auth_rule}}';
/** /**
* @var Cache|array|string the cache used to improve RBAC performance. This can be one of the following: * @var CacheInterface|array|string the cache used to improve RBAC performance. This can be one of the following:
* *
* - an application component ID (e.g. `cache`) * - an application component ID (e.g. `cache`)
* - a configuration array * - a configuration array
@ -111,7 +111,7 @@ class DbManager extends BaseManager
parent::init(); parent::init();
$this->db = Instance::ensure($this->db, Connection::className()); $this->db = Instance::ensure($this->db, Connection::className());
if ($this->cache !== null) { if ($this->cache !== null) {
$this->cache = Instance::ensure($this->cache, Cache::className()); $this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface');
} }
} }
@ -968,7 +968,7 @@ class DbManager extends BaseManager
public function loadFromCache() public function loadFromCache()
{ {
if ($this->items !== null || !$this->cache instanceof Cache) { if ($this->items !== null || !$this->cache instanceof CacheInterface) {
return; return;
} }

View File

@ -8,7 +8,7 @@
namespace yii\web; namespace yii\web;
use Yii; use Yii;
use yii\caching\Cache; use yii\caching\CacheInterface;
use yii\di\Instance; use yii\di\Instance;
/** /**
@ -39,7 +39,7 @@ use yii\di\Instance;
class CacheSession extends Session class CacheSession extends Session
{ {
/** /**
* @var Cache|array|string the cache object or the application component ID of the cache object. * @var CacheInterface|array|string the cache object or the application component ID of the cache object.
* The session data will be stored using this cache object. * The session data will be stored using this cache object.
* *
* After the CacheSession object is created, if you want to change this property, * After the CacheSession object is created, if you want to change this property,
@ -56,7 +56,7 @@ class CacheSession extends Session
public function init() public function init()
{ {
parent::init(); parent::init();
$this->cache = Instance::ensure($this->cache, Cache::className()); $this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface');
} }
/** /**

View File

@ -10,7 +10,7 @@ namespace yii\web;
use Yii; use Yii;
use yii\base\Component; use yii\base\Component;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
use yii\caching\Cache; use yii\caching\CacheInterface;
use yii\helpers\Url; use yii\helpers\Url;
/** /**
@ -118,7 +118,7 @@ class UrlManager extends Component
*/ */
public $routeParam = 'r'; public $routeParam = 'r';
/** /**
* @var Cache|string the cache object or the application component ID of the cache object. * @var CacheInterface|string the cache object or the application component ID of the cache object.
* Compiled URL rules will be cached through this cache object, if it is available. * Compiled URL rules will be cached through this cache object, if it is available.
* *
* After the UrlManager object is created, if you want to change this property, * After the UrlManager object is created, if you want to change this property,
@ -181,7 +181,7 @@ class UrlManager extends Component
if (is_string($this->cache)) { if (is_string($this->cache)) {
$this->cache = Yii::$app->get($this->cache, false); $this->cache = Yii::$app->get($this->cache, false);
} }
if ($this->cache instanceof Cache) { if ($this->cache instanceof CacheInterface) {
$cacheKey = $this->cacheKey; $cacheKey = $this->cacheKey;
$hash = md5(json_encode($this->rules)); $hash = md5(json_encode($this->rules));
if (($data = $this->cache->get($cacheKey)) !== false && isset($data[1]) && $data[1] === $hash) { if (($data = $this->cache->get($cacheKey)) !== false && isset($data[1]) && $data[1] === $hash) {

View File

@ -9,7 +9,7 @@ namespace yii\widgets;
use Yii; use Yii;
use yii\base\Widget; use yii\base\Widget;
use yii\caching\Cache; use yii\caching\CacheInterface;
use yii\caching\Dependency; use yii\caching\Dependency;
use yii\di\Instance; use yii\di\Instance;
@ -25,7 +25,7 @@ use yii\di\Instance;
class FragmentCache extends Widget class FragmentCache extends Widget
{ {
/** /**
* @var Cache|array|string the cache object or the application component ID of the cache object. * @var CacheInterface|array|string the cache object or the application component ID of the cache object.
* After the FragmentCache object is created, if you want to change this property, * After the FragmentCache object is created, if you want to change this property,
* you should only assign it with a cache object. * you should only assign it with a cache object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
@ -84,9 +84,9 @@ class FragmentCache extends Widget
{ {
parent::init(); parent::init();
$this->cache = $this->enabled ? Instance::ensure($this->cache, Cache::className()) : null; $this->cache = $this->enabled ? Instance::ensure($this->cache, 'yii\caching\CacheInterface') : null;
if ($this->cache instanceof Cache && $this->getCachedContent() === false) { if ($this->cache instanceof CacheInterface && $this->getCachedContent() === false) {
$this->getView()->cacheStack[] = $this; $this->getView()->cacheStack[] = $this;
ob_start(); ob_start();
ob_implicit_flush(false); ob_implicit_flush(false);
@ -103,7 +103,7 @@ class FragmentCache extends Widget
{ {
if (($content = $this->getCachedContent()) !== false) { if (($content = $this->getCachedContent()) !== false) {
echo $content; echo $content;
} elseif ($this->cache instanceof Cache) { } elseif ($this->cache instanceof CacheInterface) {
array_pop($this->getView()->cacheStack); array_pop($this->getView()->cacheStack);
$content = ob_get_clean(); $content = ob_get_clean();
@ -140,7 +140,7 @@ class FragmentCache extends Widget
$this->_content = false; $this->_content = false;
if (!($this->cache instanceof Cache)) { if (!($this->cache instanceof CacheInterface)) {
return $this->_content; return $this->_content;
} }

View File

@ -23,7 +23,7 @@ function microtime($float = false)
namespace yiiunit\framework\caching; namespace yiiunit\framework\caching;
use yii\caching\Cache; use yii\caching\CacheInterface;
use yii\caching\TagDependency; use yii\caching\TagDependency;
use yiiunit\TestCase; use yiiunit\TestCase;
@ -45,7 +45,7 @@ abstract class CacheTestCase extends TestCase
/** /**
* @return Cache * @return CacheInterface
*/ */
abstract protected function getCacheInstance(); abstract protected function getCacheInstance();
@ -62,7 +62,7 @@ abstract class CacheTestCase extends TestCase
} }
/** /**
* @return Cache * @return CacheInterface
*/ */
public function prepare() public function prepare()
{ {