Skip to content

Commit

Permalink
Fixes yiisoft#14081: Added yii\caching\CacheInterface to make custo…
Browse files Browse the repository at this point in the history
…m cache extensions adoption easier
  • Loading branch information
SilverFire authored and samdark committed Jun 11, 2017
1 parent 2b7e8be commit cb53b2f
Show file tree
Hide file tree
Showing 22 changed files with 249 additions and 61 deletions.
1 change: 1 addition & 0 deletions framework/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Yii Framework 2 Change Log
- Enh #14089: Added tests for `yii\base\Theme` (vladis84)
- Enh #13586: Added `$preserveNonEmptyValues` property to the `yii\behaviors\AttributeBehavior` (Kolyunya)
- 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
--------------------
Expand Down
4 changes: 2 additions & 2 deletions framework/base/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
* @property \yii\rbac\ManagerInterface $authManager The auth manager application component. Null is returned
* if auth manager is not configured. This property is read-only.
* @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.
* @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.
Expand Down Expand Up @@ -516,7 +516,7 @@ public function getErrorHandler()

/**
* 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()
{
Expand Down
2 changes: 1 addition & 1 deletion framework/caching/Cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
* @author Qiang Xue <qiang.xue@gmail.com>
* @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.
Expand Down
187 changes: 187 additions & 0 deletions framework/caching/CacheInterface.php
Original file line number Diff line number Diff line change
@@ -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);
}
4 changes: 2 additions & 2 deletions framework/caching/ChainedDependency.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class ChainedDependency extends 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)
{
Expand All @@ -49,7 +49,7 @@ public function evaluateDependency($cache)
/**
* Generates the data needed to determine if dependency has been changed.
* 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.
*/
protected function generateDependencyData($cache)
Expand Down
4 changes: 2 additions & 2 deletions framework/caching/DbDependency.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class DbDependency extends Dependency
/**
* Generates the data needed to determine if dependency has been changed.
* 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.
* @throws InvalidConfigException if [[db]] is not a valid application component ID
*/
Expand All @@ -66,4 +66,4 @@ protected function generateDependencyData($cache)

return $result;
}
}
}
4 changes: 2 additions & 2 deletions framework/caching/DbQueryDependency.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class DbQueryDependency extends Dependency
/**
* Generates the data needed to determine if dependency is changed.
* 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.
* @throws InvalidConfigException on invalid configuration.
*/
Expand Down Expand Up @@ -106,4 +106,4 @@ private function executeQuery($query, $db)
}
return call_user_func($this->method, $query, $db);
}
}
}
6 changes: 3 additions & 3 deletions framework/caching/Dependency.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ abstract class Dependency extends \yii\base\Object
/**
* Evaluates the dependency by generating and saving the data related with dependency.
* 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)
{
Expand All @@ -68,7 +68,7 @@ public function getHasChanged($cache)

/**
* 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.
* @since 2.0.11
*/
Expand Down Expand Up @@ -111,7 +111,7 @@ protected function generateReusableHash()
/**
* Generates the data needed to determine if dependency is changed.
* 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.
*/
abstract protected function generateDependencyData($cache);
Expand Down
2 changes: 1 addition & 1 deletion framework/caching/ExpressionDependency.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class ExpressionDependency extends Dependency
/**
* Generates the data needed to determine if dependency has been changed.
* 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.
*/
protected function generateDependencyData($cache)
Expand Down
2 changes: 1 addition & 1 deletion framework/caching/FileDependency.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class FileDependency extends Dependency
/**
* Generates the data needed to determine if dependency has been changed.
* 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.
* @throws InvalidConfigException if [[fileName]] is not set
*/
Expand Down
8 changes: 4 additions & 4 deletions framework/caching/TagDependency.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class TagDependency extends Dependency
/**
* Generates the data needed to determine if dependency has been changed.
* 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.
*/
protected function generateDependencyData($cache)
Expand Down Expand Up @@ -68,7 +68,7 @@ public function isChanged($cache)

/**
* 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
*/
public static function invalidate($cache, $tags)
Expand All @@ -82,7 +82,7 @@ public static function invalidate($cache, $tags)

/**
* Generates the timestamp for the specified cache keys.
* @param Cache $cache
* @param CacheInterface $cache
* @param string[] $keys
* @return array the timestamp indexed by cache keys
*/
Expand All @@ -99,7 +99,7 @@ protected static function touchKeys($cache, $keys)

/**
* Returns the timestamps for the specified tags.
* @param Cache $cache
* @param CacheInterface $cache
* @param string[] $tags
* @return array the timestamps indexed by the specified tags.
*/
Expand Down
6 changes: 3 additions & 3 deletions framework/console/controllers/CacheController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@

use Yii;
use yii\caching\ApcCache;
use yii\caching\CacheInterface;
use yii\console\Controller;
use yii\caching\Cache;
use yii\helpers\Console;
use yii\console\Exception;

Expand Down Expand Up @@ -265,7 +265,7 @@ private function findCaches(array $cachesNames = [])
continue;
}

if ($component instanceof Cache) {
if ($component instanceof CacheInterface) {
$caches[$name] = get_class($component);
} elseif (is_array($component) && isset($component['class']) && $this->isCacheClass($component['class'])) {
$caches[$name] = $component['class'];
Expand All @@ -284,7 +284,7 @@ private function findCaches(array $cachesNames = [])
*/
private function isCacheClass($className)
{
return is_subclass_of($className, Cache::className());
return is_subclass_of($className, 'yii\caching\CacheInterface');
}

/**
Expand Down
2 changes: 1 addition & 1 deletion framework/db/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -903,7 +903,7 @@ protected function queryInternal($method, $fetchMode = null)
if ($method !== '') {
$info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency);
if (is_array($info)) {
/* @var $cache \yii\caching\Cache */
/* @var $cache \yii\caching\CacheInterface */
$cache = $info[0];
$cacheKey = [
__CLASS__,
Expand Down
Loading

0 comments on commit cb53b2f

Please sign in to comment.