diff --git a/.gitignore b/.gitignore index a7fc91d63..f146c8613 100644 --- a/.gitignore +++ b/.gitignore @@ -6,7 +6,9 @@ .*.sw* .*.un~ nbproject +doc/html/ tmp/ +zf-mkdoc-theme/ clover.xml composer.lock diff --git a/README.md b/README.md index 4202d481f..94ba90626 100644 --- a/README.md +++ b/README.md @@ -9,4 +9,4 @@ storage adapters (DB, File, Memcache, etc). - File issues at https://github.com/zendframework/zend-cache/issues -- Documentation is at http://framework.zend.com/manual/current/en/index.html#zend-cache +- Documentation is at https://zendframework.github.io/zend-cache/ diff --git a/doc/book/index.html b/doc/book/index.html new file mode 100644 index 000000000..62abc356b --- /dev/null +++ b/doc/book/index.html @@ -0,0 +1,11 @@ +
+
+

zend-cache

+ +

Caching implementation with a variety of storage options, as well as + codified caching strategies for callbacks, classes, and output.

+ +
$ composer require zendframework/zend-cache
+
+
+ diff --git a/doc/book/index.md b/doc/book/index.md new file mode 120000 index 000000000..fe8400541 --- /dev/null +++ b/doc/book/index.md @@ -0,0 +1 @@ +../../README.md \ No newline at end of file diff --git a/doc/book/pattern/callback-cache.md b/doc/book/pattern/callback-cache.md new file mode 100644 index 000000000..54ff4ad7c --- /dev/null +++ b/doc/book/pattern/callback-cache.md @@ -0,0 +1,92 @@ +# CallbackCache + + +The callback cache pattern caches the results of arbitrary PHP callables. + +## Quick Start + +```php +use Zend\Cache\PatternFactory; +use Zend\Cache\Pattern\PatternOptions; + +// Via the factory: +$callbackCache = PatternFactory::factory('callback', [ + 'storage' => 'apc', + 'cache_output' => true, +]); + +// Or the equivalent manual instantiation: +$callbackCache = new \Zend\Cache\Pattern\CallbackCache(); +$callbackCache->setOptions(new PatternOptions([ + 'storage' => 'apc', + 'cache_output' => true, +])); +``` + +## Configuration Options + +Option | Data Type | Default Value | Description +------ | --------- | ------------- | ----------- +`storage` | `string | array | Zend\Cache\Storage\StorageInterface` | none | Adapter used for reading and writing cached data. +`cache_output` | `boolean` | `true` | Whether or not to cache callback output. + +## Available Methods + +In addition to the methods defined in the `PatternInterface`, this +implementation provides the following methods. + +```php +namespace Zend\Cache\Pattern; + +use Zend\Cache\Exception; +use Zend\Stdlib\ErrorHandler; + +class CallbackCache extends AbstractPattern +{ + /** + * Call the specified callback or get the result from cache + * + * @param callable $callback A valid callback + * @param array $args Callback arguments + * @return mixed Result + * @throws Exception\RuntimeException if invalid cached data + * @throws \Exception + */ + public function call($callback, array $args = []); + + /** + * Intercept method overloading; proxies to call() + * + * @param string $function Function name to call + * @param array $args Function arguments + * @return mixed + * @throws Exception\RuntimeException + * @throws \Exception + */ + public function __call($function, array $args); + + /** + * Generate a unique key in base of a key representing the callback part + * and a key representing the arguments part. + * + * @param callable $callback A valid callback + * @param array $args Callback arguments + * @return string + * @throws Exception\RuntimeException + * @throws Exception\InvalidArgumentException + */ + public function generateKey($callback, array $args = []); +} +``` + +## Examples + +### Instantiating the callback cache pattern + +```php +use Zend\Cache\PatternFactory; + +$callbackCache = PatternFactory::factory('callback', [ + 'storage' => 'apc' +]); +``` diff --git a/doc/book/pattern/capture-cache.md b/doc/book/pattern/capture-cache.md new file mode 100644 index 000000000..dc533b03b --- /dev/null +++ b/doc/book/pattern/capture-cache.md @@ -0,0 +1,145 @@ +# CaptureCache + +The `CaptureCache` pattern is useful for generating static resources to return +via HTTP request. When used in such a fashion, the web server needs to be +configured to run a PHP script generating the requested resource so that +subsequent requests for the same resource can be shipped without calling PHP +again. + +This pattern comes with basic logic for managing generated resources. + +## Quick Start + +For use with an Apache 404 handler: + +```apacheconf +# .htdocs +ErrorDocument 404 /index.php +``` + +```php +// index.php +use Zend\Cache\PatternFactory; +$capture = Zend\Cache\PatternFactory::factory('capture', [ + 'public_dir' => __DIR__, +]); + +// Start capturing all output, excluding headers, and write to the public +// directory: +$capture->start(); + +// Don't forget to change the HTTP response code +header('Status: 200', true, 200); + +// do stuff to dynamically generate output +``` + +## Configuration Options + +Option | Data Type | Default Value | Description +------ | --------- | ------------- | ----------- +`public_dir` | `string` | none | Location of the public web root directory in which to write output. +`index_filename` | `string` | "index.html" | The name of the index file if only a directory was requested. +`file_locking` | `bool` | `true` | Whether or not to lock output files when writing. +`file_permission` | `int | bool` | `0600` (`false` on Windows) | Default permissions for generated output files. +`dir_permission` | `int | bool` | `0700` (`false` on Windows) | Default permissions for generated output directories. +`umask` | `int` | `bool` | `false` | Whether or not to umask generated output files / directories. + +## Available Methods + +In addition to the methods exposed in `PatternInterface`, this implementation +exposes the following methods. + +```php +namespace Zend\Cache\Pattern; + +use Zend\Cache\Exception; +use Zend\Stdlib\ErrorHandler; + +class CaptureCache extends AbstractPattern +{ + /** + * Start the cache. + * + * @param string $pageId Page identifier + * @return void + */ + public function start($pageId = null); + + /** + * Write a page to the requested path. + * + * @param string $content + * @param null|string $pageId + * @throws Exception\LogicException + */ + public function set($content, $pageId = null); + + /** + * Retrieve a generated page from the cache. + * + * @param null|string $pageId + * @return string|null + * @throws Exception\LogicException + * @throws Exception\RuntimeException + */ + public function get($pageId = null); + + /** + * Check if a cache exists for the given page. + * + * @param null|string $pageId + * @throws Exception\LogicException + * @return bool + */ + public function has($pageId = null); + + /** + * Remove a page from the cache. + * + * @param null|string $pageId + * @throws Exception\LogicException + * @throws Exception\RuntimeException + * @return bool + */ + public function remove($pageId = null); + + /** + * Clear cached pages that match the specified glob pattern. + * + * @param string $pattern + * @throws Exception\LogicException + */ + public function clearByGlob($pattern = '**'); + + /** + * Returns the generated file name. + * + * @param null|string $pageId + * @return string + */ + public function getFilename($pageId = null); +} +``` + +## Examples + +### Scaling images in the web root + +Using the following Apache 404 configuration: + +```apacheconf +# .htdocs +ErrorDocument 404 /index.php +``` + +Use the following script: + +```php +// index.php +$captureCache = Zend\Cache\PatternFactory::factory('capture', [ + 'public_dir' => __DIR__, +]); + +// TODO +``` diff --git a/doc/book/pattern/class-cache.md b/doc/book/pattern/class-cache.md new file mode 100644 index 000000000..6d87b948f --- /dev/null +++ b/doc/book/pattern/class-cache.md @@ -0,0 +1,150 @@ +# ClassCache + +The `ClassCache` pattern is an extension to the +[`CallbackCache`](callback-cache.md) pattern. It has the same methods, but +instead generates the callbacks for any public static method invoked on the +class being cached, and caches static properties. + +## Quick Start + +```php +use Zend\Cache\PatternFactory; + +$classCache = PatternFactory::factory('class', [ + 'class' => 'MyClass', + 'storage' => 'apc', +]); +``` + +## Configuration Options + +Option | Data Type | Default Value | Description +------ | --------- | ------------- | ----------- +`storage` | `string | array | Zend\Cache\Storage\StorageInterface` | none | Adapter used for reading and writing cached data. +`class` | `string` | none | Name of the class for which to cache method output. +`cache_output` | `boolean` | `true` | Whether or not to cache method output. +`cache_by_default` | `boolean` | `true` | Cache all method calls by default. +`class_cache_methods` | `array` | `[]` | List of methods to cache (if `cache_by_default` is disabled). +`class_non_cache_methods` | `array` | `[]` | List of methods to omit from caching (if `cache_by_default` is enabled). + +## Available Methods + +In addition to the methods defined in `PatternInterface`, this implementation +exposes the following methods. + +```php +namespace Zend\Cache\Pattern; + +use Zend\Cache; +use Zend\Cache\Exception; + +class ClassCache extends CallbackCache +{ + /** + * Call and cache a class method + * + * @param string $method Method name to call + * @param array $args Method arguments + * @return mixed + * @throws Exception\RuntimeException + * @throws \Exception + */ + public function call($method, array $args = []); + + /** + * Intercept method overloading; proxies to call(). + * + * @param string $method Method name to call + * @param array $args Method arguments + * @return mixed + * @throws Exception\RuntimeException + * @throws \Exception + */ + public function __call($method, array $args) + { + return $this->call($method, $args); + } + + /** + * Generate a unique key in base of a key representing the callback part + * and a key representing the arguments part. + * + * @param string $method The method + * @param array $args Callback arguments + * @return string + * @throws Exception\RuntimeException + */ + public function generateKey($method, array $args = []); + + /** + * Property overloading: set a static property. + * + * @param string $name + * @param mixed $value + * @return void + * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members + */ + public function __set($name, $value) + { + $class = $this->getOptions()->getClass(); + $class::$name = $value; + } + + /** + * Property overloading: get a static property. + * + * @param string $name + * @return mixed + * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members + */ + public function __get($name) + { + $class = $this->getOptions()->getClass(); + return $class::$name; + } + + /** + * Property overloading: does the named static property exist? + * + * @param string $name + * @return bool + */ + public function __isset($name) + { + $class = $this->getOptions()->getClass(); + return isset($class::$name); + } + + /** + * Property overloading: unset a static property. + * + * @param string $name + * @return void + */ + public function __unset($name) + { + $class = $this->getOptions()->getClass(); + unset($class::$name); + } +} +``` + +## Examples + +**Caching of import feeds** + +```php +$cachedFeedReader = Zend\Cache\PatternFactory::factory('class', [ + 'class' => 'Zend\Feed\Reader\Reader', + 'storage' => 'apc', + + // The feed reader doesn't output anything, + // so the output doesn't need to be caught and cached: + 'cache_output' => false, +]); + +$feed = $cachedFeedReader->call("import", array('http://www.planet-php.net/rdf/')); + +// OR +$feed = $cachedFeedReader->import('http://www.planet-php.net/rdf/'); +``` diff --git a/doc/book/pattern/intro.md b/doc/book/pattern/intro.md new file mode 100644 index 000000000..8d2e60677 --- /dev/null +++ b/doc/book/pattern/intro.md @@ -0,0 +1,66 @@ +# Zend\\Cache\\Pattern + +Cache patterns are configurable objects that solve known performance +bottlenecks. Each should be used only in the specific situations they are +designed to address. For example, you can use the `CallbackCache`, +`ObjectCache`, or `ClassCache` patterns to cache method and function calls; to +cache output generation, the `OutputCache` pattern could assist. + +All cache patterns implement `Zend\Cache\Pattern\PatternInterface`, and most +extend the abstract class `Zend\Cache\Pattern\AbstractPattern`, which provides +common logic. + +Configuration is provided via the `Zend\Cache\Pattern\PatternOptions` class, +which can be instantiated with an associative array of options passed to the +constructor. To configure a pattern object, you can provide a +`Zend\Cache\Pattern\PatternOptions` instance to the `setOptions()` method, or +provide your options (either as an associative array or `PatternOptions` +instance) to the second argument of the factory. + +It's also possible to use a single instance of +`Zend\Cache\Pattern\PatternOptions` and pass it to multiple pattern objects. + +## Quick Start + +Pattern objects can either be created from the provided `Zend\Cache\PatternFactory`, or +by instantiating one of the `Zend\Cache\Pattern\*Cache` classes. + +```php +// Via the factory: +$callbackCache = Zend\Cache\PatternFactory::factory('callback', [ + 'storage' => 'apc', +]); + +// Or the equivalent manual instantiation: +$callbackCache = new Zend\Cache\Pattern\CallbackCache(); +$callbackCache->setOptions(new Zend\Cache\Pattern\PatternOptions([ + 'storage' => 'apc', +])); +``` + +## Available Methods + +The following methods are implemented by `Zend\Cache\Pattern\AbstractPattern`. +Please read documentation of specific patterns to get more information. + +```php +namespace Zend\Cache\Pattern; + +interface PatternInterface +{ + /** + * Set pattern options + * + * @param PatternOptions $options + * @return PatternInterface + */ + public function setOptions(PatternOptions $options); + + /** + * Get all pattern options + * + * @return PatternOptions + */ + public function getOptions(); +} +``` diff --git a/doc/book/pattern/object-cache.md b/doc/book/pattern/object-cache.md new file mode 100644 index 000000000..de8317865 --- /dev/null +++ b/doc/book/pattern/object-cache.md @@ -0,0 +1,171 @@ +# ObjectCache + +The `ObjectCache` pattern is an extension to the `CallbackCache` pattern. It has +the same methods, but instead caches output from any instance method calls or +public properties. + +## Quick Start + +```php +use stdClass; +use Zend\Cache\PatternFactory; + +$object = new stdClass(); +$objectCache = PatternFactory::factory('object', [ + 'object' => $object, + 'storage' => 'apc' +]); +``` + +## Configuration Options + +Option | Data Type | Default Value | Description +------ | --------- | ------------- | ----------- +`storage` | `string | array | Zend\Cache\Storage\StorageInterface` | none | Adapter used for reading and writing cached data. +`object` | `object` | none | The object for which to cache method calls. +`object_key` | `null | string` | Class name of object | Hopefully unique! +`cache_output` | `boolean` | `true` | Whether or not to cache method output. +`cache_by_default` | `boolean` | `true` | Cache all method calls by default. +`object_cache_methods` | `array` | `[]` | List of methods to cache (if `cache_by_default` is disabled). +`object_non_cache_methods` | `array` | `[]` | List of methods to blacklist (if `cache_by_default` is enabled). +`object_cache_magic_properties` | `boolean` | `false` | Whether or not to cache properties exposed by method overloading. + +## Available Methods + +In addition to the methods defined in `PatternInterface`, this implementation +defines the following methods. + +```php +namespace Zend\Cache\Pattern; + +use Zend\Cache\Exception; + +class ObjectCache extends CallbackCache +{ + /** + * Call and cache a class method + * + * @param string $method Method name to call + * @param array $args Method arguments + * @return mixed + * @throws Exception\RuntimeException + * @throws \Exception + */ + public function call($method, array $args = []); + + /** + * Method overloading: proxies to call(). + * + * @param string $method Method name to call + * @param array $args Method arguments + * @return mixed + * @throws Exception\RuntimeException + * @throws \Exception + */ + public function __call($method, array $args); + + /** + * Generate a unique key in base of a key representing the callback part + * and a key representing the arguments part. + * + * @param string $method The method + * @param array $args Callback arguments + * @return string + * @throws Exception\RuntimeException + */ + public function generateKey($method, array $args = []); + + /** + * Property overloading: write data to a named property. + * + * NOTE: + * Magic properties will be cached too if the option cacheMagicProperties + * is enabled and the property doesn't exist in real. If so it calls __set + * and removes cached data of previous __get and __isset calls. + * + * @param string $name + * @param mixed $value + * @return void + * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members + */ + public function __set($name, $value); + + /** + * Property overloading: read data from a named property. + * + * NOTE: + * Magic properties will be cached too if the option cacheMagicProperties + * is enabled and the property doesn't exist in real. If so it calls __get. + * + * @param string $name + * @return mixed + * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members + */ + public function __get($name); + + /** + * Property overloading: check if a named property exists. + * + * NOTE: + * Magic properties will be cached too if the option cacheMagicProperties + * is enabled and the property doesn't exist in real. If so it calls __get. + * + * @param string $name + * @return bool + * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members + */ + public function __isset($name); + + /** + * Property overloading: unset a named property. + * + * NOTE: + * Magic properties will be cached too if the option cacheMagicProperties + * is enabled and the property doesn't exist in real. If so it removes + * previous cached __isset and __get calls. + * + * @param string $name + * @return void + * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members + */ + public function __unset($name); + + /** + * Handle casting to string + * + * @return string + * @see http://php.net/manual/language.oop5.magic.php#language.oop5.magic.tostring + */ + public function __toString(); + + /** + * Intercept and cache invokable usage. + * + * @return mixed + * @see http://php.net/manual/language.oop5.magic.php#language.oop5.magic.invoke + */ + public function __invoke(); +} +``` + +## Examples + +### Caching a filter + +```php +$filter = new Zend\Filter\RealPath(); +$cachedFilter = Zend\Cache\PatternFactory::factory('object', [ + 'object' => $filter, + 'object_key' => 'RealpathFilter', + 'storage' => 'apc', + + // The realpath filter doesn't output anything + // so the output don't need to be caught and cached + 'cache_output' => false, +]); + +$path = $cachedFilter->call("filter", ['/www/var/path/../../mypath']); + +// OR +$path = $cachedFilter->filter('/www/var/path/../../mypath'); +``` diff --git a/doc/book/pattern/output-cache.md b/doc/book/pattern/output-cache.md new file mode 100644 index 000000000..6619fa6be --- /dev/null +++ b/doc/book/pattern/output-cache.md @@ -0,0 +1,66 @@ +# OutputCache + +The `OutputCache` pattern caches output between calls to `start()` and `end()`. + +## Quick Start + +```php +use Zend\Cache\PatternFactory; + +$outputCache = PatternFactory::factory('output', [ + 'storage' => 'apc' +]); +``` +## Configuration Options + +Option | Data Type | Default Value | Description +------ | --------- | ------------- | ----------- +`storage` | `string | array | Zend\Cache\Storage\StorageInterface` | none | Adapter used for reading and writing cached data. + +## Available Methods + +In addition to the methods defined in `PatternInterface`, this implementation +defines the following methods. + +```php +namespace Zend\Cache\Pattern; + +use Zend\Cache\Exception; + +class OutputCache extends AbstractPattern +{ + /** + * If there is a cached item with the given key, display its data, and + * return true. Otherwise, start buffering output until end() is called, or + * the script ends. + * + * @param string $key Key + * @throws Exception\MissingKeyException if key is missing + * @return bool + */ + public function start($key); + + /** + * Stop buffering output, write buffered data to the cache using the key + * provided to start(), and display the buffer. + * + * @throws Exception\RuntimeException if output cache not started or buffering not active + * @return bool TRUE on success, FALSE on failure writing to cache + */ + public function end(); +} +``` + +## Examples + +### Caching simple view scripts + +```php +$outputCache = Zend\Cache\PatternFactory::factory('output', [ + 'storage' => 'apc', +]); + +$outputCache->start('mySimpleViewScript'); +include '/path/to/view/script.phtml'; +$outputCache->end(); +``` diff --git a/doc/book/storage/adapter.md b/doc/book/storage/adapter.md new file mode 100644 index 000000000..fbd4d5b8c --- /dev/null +++ b/doc/book/storage/adapter.md @@ -0,0 +1,1029 @@ +# Adapters + +Storage adapters are wrappers for real storage resources such as memory or the filesystem, using +the well known *adapter* pattern. + +They come with tons of methods to read, write, and modify stored items, and to get information about +stored items and the storage. + +All adapters implement `Zend\Cache\Storage\StorageInterface`, and most extend +`Zend\Cache\Storage\Adapter\AbstractAdapter`, which provides a foundation of +common logic. + +Configuration is handled by either `Zend\Cache\Storage\Adapter\AdapterOptions`, +or an adapter-specific options class if it exists. You may pass the options +instance to the class at instantiation, via the `setOptions()` method, or, +alternately, pass an associative array of options in either place (internally, +these are then passed to an options class instance). Alternately, you can pass +either the options instance or associative array to the +`Zend\Cache\StorageFactory::factory` method. + +> ### Many methods throw exceptions +> +> Because many caching operations throw an exception on error, you need to catch +> them. You can do so manually, or you can use the plugin +> `Zend\Cache\Storage\Plugin\ExceptionHandler` with `throw_exceptions` set to +> `false` to automatically catch them. You can also define an +> `exception_callback` to log exceptions. + +## Quick Start + +Caching adapters can either be created from the provided +`Zend\Cache\StorageFactory`, or by instantiating one of the +`Zend\Cache\Storage\Adapter\*` classes. To make life easier, the +`Zend\Cache\StorageFactory` comes with a `factory()` method to create an adapter +and all requested plugins at once. + +```php +use Zend\Cache\StorageFactory; + +// Via factory: +$cache = StorageFactory::factory([ + 'adapter' => [ + 'name' => 'apc', + 'options' => ['ttl' => 3600], + ], + 'plugins' => [ + 'exception_handler' => ['throw_exceptions' => false], + ], +]); + +// Alternately, create the adapter and plugin separately: +$cache = StorageFactory::adapterFactory('apc', ['ttl' => 3600]); +$plugin = StorageFactory::pluginFactory('exception_handler', [ + 'throw_exceptions' => false, +]); +$cache->addPlugin($plugin); + +// Or do it completely manually: +$cache = new Zend\Cache\Storage\Adapter\Apc(); +$cache->getOptions()->setTtl(3600); + +$plugin = new Zend\Cache\Storage\Plugin\ExceptionHandler(); +$plugin->getOptions()->setThrowExceptions(false); +$cache->addPlugin($plugin); +``` + +## Basic Configuration Options + +The following configuration options are defined by `Zend\Cache\Storage\Adapter\AdapterOptions` and +are available for every supported adapter. Adapter-specific configuration options are described on +adapter level below. + +Option | Data Type | Default Value | Description +------ | --------- | ------------- | ----------- +`ttl` | `integer` | `0` | Time to live +`namespace` | `string` | “zfcache” | The “namespace” in which cache items will live +`key_pattern` | `null|string` | `null` | Pattern against which to validate cache keys +`readable` | `boolean` | `true` | Enable/Disable reading data from cache +`writable` | `boolean` | `true` | Enable/Disable writing data to cache + +## The StorageInterface + +`Zend\Cache\Storage\StorageInterface` is the basic interface implemented by all +storage adapters. + +```php +namespace Zend\Cache\Storage; + +use Traversable; + +interface StorageInterface +{ + /** + * Set options. + * + * @param array|Traversable|Adapter\AdapterOptions $options + * @return StorageInterface Fluent interface + */ + public function setOptions($options); + + /** + * Get options + * + * @return Adapter\AdapterOptions + */ + public function getOptions(); + + /* reading */ + + /** + * Get an item. + * + * @param string $key + * @param bool $success + * @param mixed $casToken + * @return mixed Data on success, null on failure + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function getItem($key, & $success = null, & $casToken = null); + + /** + * Get multiple items. + * + * @param array $keys + * @return array Associative array of keys and values + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function getItems(array $keys); + + /** + * Test if an item exists. + * + * @param string $key + * @return bool + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function hasItem($key); + + /** + * Test multiple items. + * + * @param array $keys + * @return array Array of found keys + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function hasItems(array $keys); + + /** + * Get metadata of an item. + * + * @param string $key + * @return array|bool Metadata on success, false on failure + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function getMetadata($key); + + /** + * Get multiple metadata + * + * @param array $keys + * @return array Associative array of keys and metadata + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function getMetadatas(array $keys); + + /* writing */ + + /** + * Store an item. + * + * @param string $key + * @param mixed $value + * @return bool + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function setItem($key, $value); + + /** + * Store multiple items. + * + * @param array $keyValuePairs + * @return array Array of not stored keys + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function setItems(array $keyValuePairs); + + /** + * Add an item. + * + * @param string $key + * @param mixed $value + * @return bool + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function addItem($key, $value); + + /** + * Add multiple items. + * + * @param array $keyValuePairs + * @return array Array of not stored keys + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function addItems(array $keyValuePairs); + + /** + * Replace an existing item. + * + * @param string $key + * @param mixed $value + * @return bool + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function replaceItem($key, $value); + + /** + * Replace multiple existing items. + * + * @param array $keyValuePairs + * @return array Array of not stored keys + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function replaceItems(array $keyValuePairs); + + /** + * Set an item only if token matches + * + * It uses the token received from getItem() to check if the item has + * changed before overwriting it. + * + * @param mixed $token + * @param string $key + * @param mixed $value + * @return bool + * @throws \Zend\Cache\Exception\ExceptionInterface + * @see getItem() + * @see setItem() + */ + public function checkAndSetItem($token, $key, $value); + + /** + * Reset lifetime of an item + * + * @param string $key + * @return bool + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function touchItem($key); + + /** + * Reset lifetime of multiple items. + * + * @param array $keys + * @return array Array of not updated keys + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function touchItems(array $keys); + + /** + * Remove an item. + * + * @param string $key + * @return bool + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function removeItem($key); + + /** + * Remove multiple items. + * + * @param array $keys + * @return array Array of not removed keys + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function removeItems(array $keys); + + /** + * Increment an item. + * + * @param string $key + * @param int $value + * @return int|bool The new value on success, false on failure + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function incrementItem($key, $value); + + /** + * Increment multiple items. + * + * @param array $keyValuePairs + * @return array Associative array of keys and new values + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function incrementItems(array $keyValuePairs); + + /** + * Decrement an item. + * + * @param string $key + * @param int $value + * @return int|bool The new value on success, false on failure + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function decrementItem($key, $value); + + /** + * Decrement multiple items. + * + * @param array $keyValuePairs + * @return array Associative array of keys and new values + * @throws \Zend\Cache\Exception\ExceptionInterface + */ + public function decrementItems(array $keyValuePairs); + + /* status */ + + /** + * Capabilities of this storage + * + * @return Capabilities + */ + public function getCapabilities(); +} +``` + +## The AvailableSpaceCapableInterface + +`Zend\Cache\Storage\AvailableSpaceCapableInterface` implements a method to allow +retrieving the current available space remaining in storage. + +```php +namespace Zend\Cache\Storage; + +interface AvailableSpaceCapableInterface +{ + /** + * Get available space in bytes + * + * @return int|float + */ + public function getAvailableSpace(); +} +``` + +## The TotalSpaceCapableInterface + +`Zend\Cache\Storage\TotalSpaceCapableInterface` implements a method to allow +retrieving the total storage space. + +```php +namespace Zend\Cache\Storage; + +interface TotalSpaceCapableInterface +{ + /** + * Get total space in bytes + * + * @return int|float + */ + public function getTotalSpace(); +} +``` + +## The ClearByNamespaceInterface + +`Zend\Cache\Storage\ClearByNamespaceInterface` implements a method to allow +clearing all cached items within a given namespace. + +```php +namespace Zend\Cache\Storage; + +interface ClearByNamespaceInterface +{ + /** + * Remove items of given namespace + * + * @param string $namespace + * @return bool + */ + public function clearByNamespace($namespace); +} +``` + +## The ClearByPrefixInterface + +`Zend\Cache\Storage\ClearByPrefixInterface` implements a method to allow +clearing all cached items that have a given prefix (within the currently +configured namespace). + +```php +namespace Zend\Cache\Storage; + +interface ClearByPrefixInterface +{ + /** + * Remove items matching given prefix + * + * @param string $prefix + * @return bool + */ + public function clearByPrefix($prefix); +} +``` +## The ClearExpiredInterface + +`Zend\Cache\Storage\ClearExpiredInterface` implements a method to allow clearing +all expired items (within the current configured namespace). + +```php +namespace Zend\Cache\Storage; + +interface ClearExpiredInterface +{ + /** + * Remove expired items + * + * @return bool + */ + public function clearExpired(); +} +``` + +## The FlushableInterface + +`Zend\Cache\Storage\FlushableInterface` implements a method for flushing the +entire cache storage. + +```php +namespace Zend\Cache\Storage; + +interface FlushableInterface +{ + /** + * Flush the whole storage + * + * @return bool + */ + public function flush(); +} +``` + +## The IterableInterface + +`Zend\Cache\Storage\IterableInterface` implements a method for retrieving an +iterator of all items in storage. It extends `IteratorAggregate`, so it's +possible to directly iterate over the storage implementations that implement +this interface using `foreach`. + +```php +namespace Zend\Cache\Storage; + +use IteratorAggregate; + +/** + * + * @method IteratorInterface getIterator() Get the storage iterator + */ +interface IterableInterface extends IteratorAggregate +{ + /** + * @return \Traversable + */ + public function getIterator(); +} +``` + +## The OptimizableInterface + +`Zend\Cache\Storage\OptimizableInterface` implements a method for running +optimization processes on the storage adapter. + +```php +namespace Zend\Cache\Storage; + +interface OptimizableInterface +{ + /** + * Optimize the storage + * + * @return bool + */ + public function optimize(); +} +``` + +## The TaggableInterface + +`Zend\Cache\Storage\TaggableInterface` implements methods for tagging items, and +cleaning (expiring) items matching tags. + +```php +namespace Zend\Cache\Storage; + +interface TaggableInterface +{ + /** + * Set tags to an item by given key. + * An empty array will remove all tags. + * + * @param string $key + * @param string[] $tags + * @return bool + */ + public function setTags($key, array $tags); + + /** + * Get tags of an item by given key + * + * @param string $key + * @return string[]|FALSE + */ + public function getTags($key); + + /** + * Remove items matching given tags. + * + * If $disjunction only one of the given tags must match + * else all given tags must match. + * + * @param string[] $tags + * @param bool $disjunction + * @return bool + */ + public function clearByTags(array $tags, $disjunction = false); +} +``` +## The Apc Adapter + +`Zend\Cache\Storage\Adapter\Apc` stores cache items in shared memory through the +PHP extension [APC](http://pecl.php.net/package/APC) (Alternative PHP Cache). + +This adapter implements the following interfaces: + +- `Zend\Cache\Storage\StorageInterface` +- `Zend\Cache\Storage\AvailableSpaceCapableInterface` +- `Zend\Cache\Storage\ClearByNamespaceInterface` +- `Zend\Cache\Storage\ClearByPrefixInterface` +- `Zend\Cache\Storage\FlushableInterface` +- `Zend\Cache\Storage\IterableInterface` +- `Zend\Cache\Storage\TotalSpaceCapableInterface` + +### Capabilities + +Capability | Value +---------- | ----- +`supportedDatatypes` | `null`, `bool`, `int`, `float`, `string`, `array` (serialized), `object` (serialized) +`supportedMetadata` | internal_key, atime, ctime, mtime, rtime, size, hits, ttl +`minTtl` | 1 +`maxTtl` | 0 +`staticTtl` | `true` +`ttlPrecision` | 1 +`useRequestTime` | value of `apc.use_request_time` from `php.ini` +`expiredRead` | `false` +`maxKeyLength` | 5182 +`namespaceIsPrefix` | `true` +`namespaceSeparator` | Option value of `namespace_separator` + +### Adapter specific options + +Name | Data Type | Default Value | Description +---- | --------- | ------------- | ----------- +`namespace_separator` | `string` | ":" | A separator for the namespace and prefix. + +## The Dba Adapter + +`Zend\Cache\Storage\Adapter\Dba` stores cache items into +[dbm](http://en.wikipedia.org/wiki/Dbm)-like databases using the PHP extension +[dba](http://php.net/manual/book.dba.php). + +This adapter implements the following interfaces: + +- `Zend\Cache\Storage\StorageInterface` +- `Zend\Cache\Storage\AvailableSpaceCapableInterface` +- `Zend\Cache\Storage\ClearByNamespaceInterface` +- `Zend\Cache\Storage\ClearByPrefixInterface` +- `Zend\Cache\Storage\FlushableInterface` +- `Zend\Cache\Storage\IterableInterface` +- `Zend\Cache\Storage\OptimizableInterface` +- `Zend\Cache\Storage\TotalSpaceCapableInterface` + +### Capabilities + +Capability | Value +---------- | ----- +`supportedDatatypes` | `string`, `null` => `string`, `boolean` => `string`, `integer` => `string`, `double` => `string` +`supportedMetadata` | none +`minTtl` | 0 +`maxKeyLength` | 0 +`namespaceIsPrefix` | `true` +`namespaceSeparator` | Option value of `namespace_separator` + +### Adapter specific options + +Name | Data Type | Default Value | Description +---- | --------- | ------------- | ----------- +`namespace_separator` | `string` | ":" | A separator for the namespace and prefix. +`pathname` | `string` | "" | Pathname to the database file. +`mode` | `string` | "c" | The mode with which to open the database; please read [dba_open](http://php.net/manual/function.dba-open.php) for more information. +`handler` | `string` | "flatfile" | The name of the handler which shall be used for accessing the database. + +> ### This adapter doesn't support automatic expiry +> +> Because this adapter doesn't support automatic expiry, it's very important to clean +> outdated items periodically! + +## The Filesystem Adapter + +`Zend\Cache\Storage\Adapter\Filesystem` stores cache items on the filesystem. + +This adapter implements the following interfaces: + +- `Zend\Cache\Storage\StorageInterface` +- `Zend\Cache\Storage\AvailableSpaceCapableInterface` +- `Zend\Cache\Storage\ClearByNamespaceInterface` +- `Zend\Cache\Storage\ClearByPrefixInterface` +- `Zend\Cache\Storage\ClearExpiredInterface` +- `Zend\Cache\Storage\FlushableInterface` +- `Zend\Cache\Storage\IterableInterface` +- `Zend\Cache\Storage\OptimizableInterface` +- `Zend\Cache\Storage\TaggableInterface` +- `Zend\Cache\Storage\TotalSpaceCapableInterface` + +### Capabilities + +Capability | Value +---------- | ----- +`supportedDatatypes` | `string`, `null` => `string`, `boolean` => `string`, `integer` => `string`, `double` => `string` +`supportedMetadata` | mtime, filespec, atime, ctime +`minTtl` | 1 +`maxTtl` | 0 +`staticTtl` | `false` +`ttlPrecision` | 1 +`useRequestTime` | `false` +`expiredRead` | `true` +`maxKeyLength` | 251 +`namespaceIsPrefix` | `true` +`namespaceSeparator` | Option value of `namespace_separator` + +### Adapter specific options + +Name | Data Type | Default Value | Description +---- | --------- | ------------- | ----------- +`namespace_separator` | `string` | ":" | A separator for the namespace and prefix +`cache_dir` | `string` | "" | Directory to store cache files. +`clear_stat_cache` | `boolean` | `true` | Call `clearstatcache()` enabled? +`dir_level` | `integer` | `1` | Defines how much sub-directories should be created. +`dir_permission` | `integer` | `false` | 0700 Set explicit permission on creating new directories. +`file_locking` | `boolean` | `true` | Lock files on writing. +`file_permission` | `integer` | `false` | 0600 Set explicit permission on creating new files. +`key_pattern` | `string` | `/^[a-z0-9_\+\-]*$/Di` | Validate key against pattern. +`no_atime` | `boolean` | `true` | Don’t get ‘fileatime’ as ‘atime’ on metadata. +`no_ctime` | `boolean` | `true` | Don’t get ‘filectime’ as ‘ctime’ on metadata. +`umask` | `integer|false` | `false` | Use [umask](http://wikipedia.org/wiki/Umask) to set file and directory permissions. + +## The Memcached Adapter + +`Zend\Cache\Storage\Adapter\Memcached` stores cache items over the memcached +protocol, using the PHP extension [memcached](http://pecl.php.net/package/memcached), +based on [Libmemcached](http://libmemcached.org/). + +This adapter implements the following interfaces: + +- `Zend\Cache\Storage\StorageInterface` +- `Zend\Cache\Storage\AvailableSpaceCapableInterface` +- `Zend\Cache\Storage\FlushableInterface` +- `Zend\Cache\Storage\TotalSpaceCapableInterface` + +### Capabilities + +Capability | Value +---------- | ----- +`supportedDatatypes` | `null`, `boolean`, `integer`, `double`, `string`, `array` (serialized), `object` (serialized) +`supportedMetadata` | none +`minTtl` | 1 +`maxTtl` | 0 +`staticTtl` | `true` +`ttlPrecision` | 1 +`useRequestTime` | `false` +`expiredRead` | `false` +`maxKeyLength` | 255 +`namespaceIsPrefix` | `true` +`namespaceSeparator` | none + +### Adapter specific options + +Name | Data Type | Default Value | Description +---- | --------- | ------------- | ----------- +`servers` | `array` | `[]` | List of servers in the format `[] = [string host, integer port]` +`lib_options` | `array` | `[]` | Associative array of Libmemcached options where the array key is the option name (without the prefix `OPT_`) or the constant value. The array value is the option value. Please read [the memcached setOption() page](http://php.net/manual/memcached.setoption.php) for more information + +## The Redis Adapter + +`Zend\Cache\Storage\Adapter\Redis` stores cache items over the redis protocol +using the PHP extension [redis](https://github.com/nicolasff/phpredis). + +This adapter implements the following interfaces: + +- `Zend\Cache\Storage\FlushableInterface` +- `Zend\Cache\Storage\TotalSpaceCapableInterface` + +### Capabilities + +Capability | Value +---------- | ----- +`supportedDatatypes` | `string`, `array` (serialized), `object` (serialized) +`supportedMetadata` | none +`minTtl` | 1 +`maxTtl` | 0 +`staticTtl` | `true` +`ttlPrecision` | 1 +`useRequestTime` | `false` +`expiredRead` | `false` +`maxKeyLength` | 255 +`namespaceIsPrefix` | `true` +`namespaceSeparator` | none + +### Adapter specific options + +Name | Data Type | Default Value | Description +---- | --------- | ------------- | ----------- +`database` | `integer` | 0 | Set database identifier. +`lib_option` | `array` | `[]` | Associative array of redis options where the array key is the option name. +`namespace_separator` | `string` | ":" | A separator for the namespace and prefix. +`password` | `string` | "" | Set password. +`persistent_id` | `string` | | Set persistent id (name of the connection, leave blank to not use a persistent connection). +`resource_manager` | `string` | | Set the redis resource manager to use +`server` | | | See below. + +`server` can be described as any of the following: + +- URI: `/path/to/sock.sock` +- Associative array: `['host' => [, 'port' => [, 'timeout' => ]]]` +- List: `[[, , [, ]]]` + +## The Memory Adapter + +The `Zend\Cache\Storage\Adapter\Memory` stores items in-memory in the current +process only. + +This adapter implements the following interfaces: + +- `Zend\Cache\Storage\StorageInterface` +- `Zend\Cache\Storage\AvailableSpaceCapableInterface` +- `Zend\Cache\Storage\ClearByPrefixInterface` +- `Zend\Cache\Storage\ClearExpiredInterface` +- `Zend\Cache\Storage\FlushableInterface` +- `Zend\Cache\Storage\IterableInterface` +- `Zend\Cache\Storage\TaggableInterface` +- `Zend\Cache\Storage\TotalSpaceCapableInterface` + +### Capabilities + +Capability | Value +---------- | ----- +`supportedDatatypes` | `string`, `null`, `boolean`, `integer`, `double`, `array`, `object`, `resource` +`supportedMetadata` | mtime +`minTtl` | 1 +`maxTtl` | Value of `PHP_INT_MAX` +`staticTtl` | `false` +`ttlPrecision` | 0.05 +`useRequestTime` | `false` +`expiredRead` | `true` +`maxKeyLength` | 0 +`namespaceIsPrefix` | `false` + +### Adapter specific options + +Name | Data Type | Default Value | Description +---- | --------- | ------------- | ----------- +`memory_limit` | `string|integer` | 50% of `memory_limit` INI value | Limit of how much memory can PHP allocate to allow store items. + +> #### Memory limit +> +> The adapter has the following behavior with regards to the memory limit: +> +> - If the consumed memory exceeds the limit provided, an `OutOfSpaceException` +> is thrown. +> - A number less the or equal to zero disables the memory limit. +> - When a value is provided for the memory limit, the value is measured in +> bytes. Shorthand notation may also be provided. + +> ### Current process only! +> +> All stored items will be lost on termination of the script. For web-facing +> requests, this typically means the cache is volatile. + +## The MongoDB Adapter + +`Zend\Cache\Storage\Adapter\MongoDB` stores cache items using MongoDB, via either the +PHP extension [mongo](http://php.net/mongo), or a MongoDB polyfill library, such as +[Mongofill](https://github.com/mongofill/mongofill). + +This adapter implements the following interfaces: + +- `Zend\Cache\Storage\FlushableInterface` + +### Capabilities + +Capability Value +supportedDatatypes null, boolean, integer, double, string, array +supportedMetadata _id +minTtl 0 +maxTtl 0 +staticTtl true +ttlPrecision 1 +useRequestTime false +expiredRead false +maxKeyLength 255 +namespaceIsPrefix true +namespaceSeparator