Zend\Cache\Storage\Adapter¶
Overview¶
Storage adapters are wrappers for real storage resources such as memory and 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 the interface
Zend\Cache\Storage\StorageInterfaceand most extendZend\Cache\Storage\Adapter\AbstractAdapter, which comes with basic 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 or via thesetOptions()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 theZend\Cache\StorageFactory::factorymethod.
Nota
Many methods throw exceptions
Because many caching operations throw an exception on error, you need to catch them manually or you can use the
plug-in 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\StorageFactoryfactory, or by simply instantiating one of theZend\Cache\Storage\Adapter\*classes.To make life easier, the
Zend\Cache\StorageFactorycomes with afactorymethod to create an adapter and create/add all requested plugins at once.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | use Zend\Cache\StorageFactory;
// Via factory:
$cache = StorageFactory::factory(array(
'adapter' => array(
'name' => 'apc',
'options' => array('ttl' => 3600),
),
'plugins' => array(
'exception_handler' => array('throw_exceptions' => false),
),
));
// Alternately:
$cache = StorageFactory::adapterFactory('apc', array('ttl' => 3600));
$plugin = StorageFactory::pluginFactory('exception_handler', array(
'throw_exceptions' => false,
));
$cache->addPlugin($plugin);
// Or 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¶
Basic 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 or via thesetOptions()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 theZend\Cache\StorageFactory::factorymethod.The following configuration options are defined by
Zend\Cache\Storage\Adapter\AdapterOptionsand are available for every supported adapter. Adapter-specific configuration options are described on adapter level below.
Option Data Type Default Value Description ttl integer0 Time to live namespace string“zfcache” The “namespace” in which cache items will live key_pattern null``|``stringnullPattern against which to validate cache keys readable booleantrueEnable/Disable reading data from cache writable booleantrueEnable/Disable writing data to cache
The StorageInterface¶
The Zend\Cache\Storage\StorageInterface is the basic interface implemented by all storage adapters.
-
getItem(string $key, boolean & $success = null, mixed & $casToken = null) Load an item with the given $key.
If item exists set parameter $success to
true, set parameter $casToken and returnsmixedvalue of item.If item can’t load set parameter $success to
falseand returnsnull.Tipo de retorno: mixed
-
getItems(array $keys) Load all items given by $keys returning key-value pairs.
Tipo de retorno: array
-
hasItem(string $key) Test if an item exists.
Tipo de retorno: boolean
-
hasItems(array $keys) Test multiple items.
Tipo de retorno: string[]
-
getMetadata(string $key) Get metadata of an item.
Tipo de retorno: array|boolean
-
getMetadatas(array $keys) Get multiple metadata.
Tipo de retorno: array
-
setItem(string $key, mixed $value) Store an item.
Tipo de retorno: boolean
-
setItems(array $keyValuePairs) Store multiple items.
Tipo de retorno: boolean
-
addItem(string $key, mixed $value) Add an item.
Tipo de retorno: boolean
-
addItems(array $keyValuePairs) Add multiple items.
Tipo de retorno: boolean
-
replaceItem(string $key, mixed $value) Replace an item.
Tipo de retorno: boolean
-
replaceItems(array $keyValuePairs) Replace multiple items.
Tipo de retorno: boolean
-
checkAndSetItem(mixed $token, string $key, mixed $value) Set item only if token matches. It uses the token received from
getItem()to check if the item has changed before overwriting it.Tipo de retorno: boolean
-
touchItem(string $key) Reset lifetime of an item.
Tipo de retorno: boolean
-
touchItems(array $keys) Reset lifetime of multiple items.
Tipo de retorno: boolean
-
removeItem(string $key) Remove an item.
Tipo de retorno: boolean
-
removeItems(array $keys) Remove multiple items.
Tipo de retorno: boolean
-
incrementItem(string $key, int $value) Increment an item.
Tipo de retorno: integer|boolean
-
incrementItems(array $keyValuePairs) Increment multiple items.
Tipo de retorno: boolean
-
decrementItem(string $key, int $value) Decrement an item.
Tipo de retorno: integer|boolean
-
decrementItems(array $keyValuePairs) Decrement multiple items.
Tipo de retorno: boolean
-
getCapabilities() Capabilities of this storage.
Tipo de retorno: Zend\Cache\Storage\Capabilities
The AvailableSpaceCapableInterface¶
The Zend\Cache\Storage\AvailableSpaceCapableInterface implements a method
to make it possible getting the current available space of the storage.
-
getAvailableSpace() Get available space in bytes.
Tipo de retorno: integer|float
The TotalSpaceCapableInterface¶
The Zend\Cache\Storage\TotalSpaceCapableInterface implements a method to
make it possible getting the total space of the storage.
-
getTotalSpace() Get total space in bytes.
Tipo de retorno: integer|float
The ClearByNamespaceInterface¶
The Zend\Cache\Storage\ClearByNamespaceInterface implements a method to
clear all items of a given namespace.
-
clearByNamespace(string $namespace) Remove items of given namespace.
Tipo de retorno: boolean
The ClearByPrefixInterface¶
The Zend\Cache\Storage\ClearByPrefixInterface implements a method to clear
all items of a given prefix (within the current configured namespace).
-
clearByPrefix(string $prefix) Remove items matching given prefix.
Tipo de retorno: boolean
The ClearExpiredInterface¶
The Zend\Cache\Storage\ClearExpiredInterface implements a method to clear
all expired items (within the current configured namespace).
-
clearExpired() Remove expired items.
Tipo de retorno: boolean
The FlushableInterface¶
The Zend\Cache\Storage\FlushableInterface implements a method to flush
the complete storage.
-
flush() Flush the whole storage.
Tipo de retorno: boolean
The IterableInterface¶
The Zend\Cache\Storage\IterableInterface implements a method to get an
iterator to iterate over items of the storage. It extends IteratorAggregate
so it’s possible to directly iterate over the storage using foreach.
-
getIterator() Get an Iterator.
Tipo de retorno: Zend\Cache\Storage\IteratorInterface
The OptimizableInterface¶
The Zend\Cache\Storage\OptimizableInterface implements a method to run
optimization processes on the storage.
-
optimize() Optimize the storage.
Tipo de retorno: boolean
The TaggableInterface¶
The Zend\Cache\Storage\TaggableInterface implements methods to mark items
with one or more tags and to clean items matching tags.
-
setTags(string $key, string[] $tags) Set tags to an item by given key. (An empty array will remove all tags)
Tipo de retorno: boolean
-
getTags(string $key) Get tags of an item by given key.
Tipo de retorno: string[]|false
-
clearByTags(string[] $tags, boolean $disjunction = false) Remove items matching given tags.
If $disjunction is
trueonly one of the given tags must match else all given tags must match.Tipo de retorno: boolean
The Apc Adapter¶
The
Zend\Cache\Storage\Adapter\Apcadapter stores cache items in shared memory through the required PHP extension APC (Alternative PHP Cache).This adapter implements the following interfaces:
Zend\Cache\Storage\StorageInterfaceZend\Cache\Storage\AvailableSpaceCapableInterfaceZend\Cache\Storage\ClearByNamespaceInterfaceZend\Cache\Storage\ClearByPrefixInterfaceZend\Cache\Storage\FlushableInterfaceZend\Cache\Storage\IterableInterfaceZend\Cache\Storage\TotalSpaceCapableInterface
| Capability | Value |
|---|---|
| supportedDatatypes | null, boolean, integer, double, string, array (serialized), object (serialized) |
| supportedMetadata | internal_key, atime, ctime, mtime, rtime, size, hits, ttl |
| minTtl | 1 |
| maxTtl | 0 |
| staticTtl | true |
| ttlPrecision | 1 |
| useRequestTime | <ini value of apc.use_request_time> |
| expiredRead | false |
| maxKeyLength | 5182 |
| namespaceIsPrefix | true |
| namespaceSeparator | <Option value of namespace_separator> |
| Name | Data Type | Default Value | Description |
|---|---|---|---|
| namespace_separator | string |
”:” | A separator for the namespace and prefix |
The Dba Adapter¶
The
Zend\Cache\Storage\Adapter\Dbaadapter stores cache items into dbm like databases using the required PHP extension dba.This adapter implements the following interfaces:
Zend\Cache\Storage\StorageInterfaceZend\Cache\Storage\AvailableSpaceCapableInterfaceZend\Cache\Storage\ClearByNamespaceInterfaceZend\Cache\Storage\ClearByPrefixInterfaceZend\Cache\Storage\FlushableInterfaceZend\Cache\Storage\IterableInterfaceZend\Cache\Storage\OptimizableInterfaceZend\Cache\Storage\TotalSpaceCapableInterface
| 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> |
| 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 to open the database Please read dba_open for more information |
| handler | string |
“flatfile” | The name of the handler which shall be used for accessing the database. |
Nota
This adapter doesn’t support automatically expire items
Because of this adapter doesn’t support automatically expire items it’s very important to clean outdated items by self.
The Filesystem Adapter¶
The
Zend\Cache\Storage\Adapter\Filesystemadapter stores cache items into the filesystem.This adapter implements the following interfaces:
Zend\Cache\Storage\StorageInterfaceZend\Cache\Storage\AvailableSpaceCapableInterfaceZend\Cache\Storage\ClearByNamespaceInterfaceZend\Cache\Storage\ClearByPrefixInterfaceZend\Cache\Storage\ClearExpiredInterfaceZend\Cache\Storage\FlushableInterfaceZend\Cache\Storage\IterableInterfaceZend\Cache\Storage\OptimizableInterfaceZend\Cache\Storage\TaggableInterfaceZend\Cache\Storage\TotalSpaceCapableInterface
| 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> |
| 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 to set file and directory permissions |
The Memcached Adapter¶
The
Zend\Cache\Storage\Adapter\Memcachedadapter stores cache items over the memcached protocol. It’s using the required PHP extension memcached which is based on Libmemcached.This adapter implements the following interfaces:
Zend\Cache\Storage\StorageInterfaceZend\Cache\Storage\AvailableSpaceCapableInterfaceZend\Cache\Storage\FlushableInterfaceZend\Cache\Storage\TotalSpaceCapableInterface
| 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> |
| Name | Data Type | Default Value | Description |
|---|---|---|---|
| servers | array |
[] |
List of servers in [] = array(string host, integer port) |
| lib_options | array |
[] |
Associative array of Libmemcached options were the array key is the option name (without the prefix “OPT_”) or the constant value. The array value is the option value Please read this<http://php.net/manual/memcached.setoption.php> for more information |
The Redis Adapter¶
The
Zend\Cache\Storage\Adapter\Redisadapter stores cache items over the redis protocol. It’s using the required PHP extension redis.This adapter implements the following interfaces:
Zend\Cache\Storage\FlushableInterfaceZend\Cache\Storage\TotalSpaceCapableInterface
| 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> |
| Name | Data Type | Default Value | Description |
|---|---|---|---|
| database | integer |
0 | Set database identifier |
| lib_option | array |
[] |
Associative array of redis options were 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 persistant id (RDB, AOF) |
|
| resource_manager | string |
Set the redis resource manager to use | |
| servers |
|
The Memory Adapter¶
The
Zend\Cache\Storage\Adapter\Memoryadapter stores cache items into the PHP process using an array.This adapter implements the following interfaces:
Zend\Cache\Storage\StorageInterfaceZend\Cache\Storage\AvailableSpaceCapableInterfaceZend\Cache\Storage\ClearByPrefixInterfaceZend\Cache\Storage\ClearExpiredInterfaceZend\Cache\Storage\FlushableInterfaceZend\Cache\Storage\IterableInterfaceZend\Cache\Storage\TaggableInterfaceZend\Cache\Storage\TotalSpaceCapableInterface
| 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 |
| Name | Data Type | Default Value | Description |
|---|---|---|---|
| memory_limit | string integer |
<50% of ini value memory_limit> |
Limit of how much memory can PHP allocate to allow store items into this adapter
|
Nota
All stored items will be lost after terminating the script.
The WinCache Adapter¶
The
Zend\Cache\Storage\Adapter\WinCacheadapter stores cache items into shared memory through the required PHP extension WinCache.This adapter implements the following interfaces:
Zend\Cache\Storage\StorageInterfaceZend\Cache\Storage\AvailableSpaceCapableInterfaceZend\Cache\Storage\FlushableInterfaceZend\Cache\Storage\TotalSpaceCapableInterface
| Capability | Value |
|---|---|
| supportedDatatypes | null, boolean, integer, double, string, array (serialized), object (serialized) |
| supportedMetadata | internal_key, ttl, hits, size |
| minTtl | 1 |
| maxTtl | 0 |
| staticTtl | true |
| ttlPrecision | 1 |
| useRequestTime | <ini value of apc.use_request_time> |
| expiredRead | false |
| namespaceIsPrefix | true |
| namespaceSeparator | <Option value of namespace_separator> |
| Name | Data Type | Default Value | Description |
|---|---|---|---|
| namespace_separator | string |
”:” | A separator for the namespace and prefix |
The XCache Adapter¶
The
Zend\Cache\Storage\Adapter\XCacheadapter stores cache items into shared memory through the required PHP extension XCache.This adapter implements the following interfaces:
Zend\Cache\Storage\StorageInterfaceZend\Cache\Storage\AvailableSpaceCapableInterfaceZend\Cache\Storage\ClearByNamespaceInterfaceZend\Cache\Storage\ClearByPrefixInterfaceZend\Cache\Storage\FlushableInterfaceZend\Cache\Storage\IterableInterfaceZend\Cache\Storage\TotalSpaceCapableInterface
| Capability | Value |
|---|---|
| supportedDatatypes | boolean, integer, double, string, array (serialized), object (serialized) |
| supportedMetadata | internal_key, size, refcount, hits, ctime, atime, hvalue |
| minTtl | 1 |
| maxTtl | <ini value of xcache.var_maxttl> |
| staticTtl | true |
| ttlPrecision | 1 |
| useRequestTime | true |
| expiredRead | false |
| maxKeyLength | 5182 |
| namespaceIsPrefix | true |
| namespaceSeparator | <Option value of namespace_separator> |
| Name | Data Type | Default Value | Description |
|---|---|---|---|
| namespace_separator | string |
”:” | A separator for the namespace and prefix |
| admin_auth | boolean |
false |
Enable admin authentication by configuration options This makes XCache administration functions accessible if |
| admin_user | string |
“” | The username of xcache.admin.user |
| admin_pass | string |
“” | The password of xcache.admin.pass in plain text |
The ZendServerDisk Adapter¶
This
Zend\Cache\Storage\Adapter\ZendServerDiskadapter stores cache items on filesystem through the Zend Server Data Caching API.This adapter implements the following interfaces:
Zend\Cache\Storage\StorageInterfaceZend\Cache\Storage\AvailableSpaceCapableInterfaceZend\Cache\Storage\ClearByNamespaceInterfaceZend\Cache\Storage\FlushableInterfaceZend\Cache\Storage\TotalSpaceCapableInterface
| Capability | Value |
|---|---|
| supportedDatatypes | null, boolean, integer, double, string, array (serialized), object (serialized) |
| supportedMetadata | <none> |
| minTtl | 1 |
| maxTtl | 0 |
| maxKeyLength | 0 |
| staticTtl | true |
| ttlPrecision | 1 |
| useRequestTime | false |
| expiredRead | false |
| namespaceIsPrefix | true |
| namespaceSeparator | :: |
The ZendServerShm Adapter¶
The
Zend\Cache\Storage\Adapter\ZendServerShmadapter stores cache items in shared memory through the Zend Server Data Caching API.This adapter implements the following interfaces:
Zend\Cache\Storage\StorageInterfaceZend\Cache\Storage\ClearByNamespaceInterfaceZend\Cache\Storage\FlushableInterfaceZend\Cache\Storage\TotalSpaceCapableInterface
| Capability | Value |
|---|---|
| supportedDatatypes | null, boolean, integer, double, string, array (serialized), object (serialized) |
| supportedMetadata | <none> |
| minTtl | 1 |
| maxTtl | 0 |
| maxKeyLength | 0 |
| staticTtl | true |
| ttlPrecision | 1 |
| useRequestTime | false |
| expiredRead | false |
| namespaceIsPrefix | true |
| namespaceSeparator | :: |
Examples¶
Basic usage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $cache = \Zend\Cache\StorageFactory::factory(array(
'adapter' => array(
'name' => 'filesystem'
),
'plugins' => array(
// Don't throw exceptions on cache errors
'exception_handler' => array(
'throw_exceptions' => false
),
)
));
$key = 'unique-cache-key';
$result = $cache->getItem($key, $success);
if (!$success) {
$result = doExpensiveStuff();
$cache->setItem($key, $result);
}
|
Get multiple rows from db
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | // Instantiate the cache instance using a namespace for the same type of items
$cache = \Zend\Cache\StorageFactory::factory(array(
'adapter' => array(
'name' => 'filesystem'
// With a namespace we can indicate the same type of items
// -> So we can simple use the db id as cache key
'options' => array(
'namespace' => 'dbtable'
),
),
'plugins' => array(
// Don't throw exceptions on cache errors
'exception_handler' => array(
'throw_exceptions' => false
),
// We store database rows on filesystem so we need to serialize them
'Serializer'
)
));
// Load two rows from cache if possible
$ids = array(1, 2);
$results = $cache->getItems($ids);
if (count($results) < count($ids)) {
// Load rows from db if loading from cache failed
$missingIds = array_diff($ids, array_keys($results));
$missingResults = array();
$query = 'SELECT * FROM dbtable WHERE id IN (' . implode(',', $missingIds) . ')';
foreach ($pdo->query($query, PDO::FETCH_ASSOC) as $row) {
$missingResults[ $row['id'] ] = $row;
}
// Update cache items of the loaded rows from db
$cache->setItems($missingResults);
// merge results from cache and db
$results = array_merge($results, $missingResults);
}
|