Class Cache
Cache provides a consistent interface to Caching in your application. It allows you to use several different Cache engines, without coupling your application to a specific implementation. It also allows you to change out cache storage or configuration without effecting the rest of your application.
Configuring Cache engines
You can configure Cache engines in your application's Config/cache.php
file.
A sample configuration would be:
Cache::config('shared', [
'className' => 'Cake\Cache\Engine\ApcEngine',
'prefix' => 'my_app_'
]);
This would configure an APC cache engine to the 'shared' alias. You could then read and write
to that cache alias by using it for the $config
parameter in the various Cache methods.
In general all Cache operations are supported by all cache engines. However, Cache::increment() and Cache::decrement() are not supported by File caching.
There are 5 built-in caching engines:
FileEngine
- Uses simple files to store content. Poor performance, but good for storing large objects, or things that are not IO sensitive. Well suited to development as it is an easy cache to inspect and manually flush.ApcEngine
- Uses the APC object cache, one of the fastest caching engines.MemcacheEngine
- Uses the PECL::Memcache extension and Memcached for storage. Fast reads/writes, and benefits from memcache being distributed.XcacheEngine
- Uses the Xcache extension, an alternative to APC.WincacheEngine
- Uses Windows Cache Extension for PHP. Supports wincache 1.1.0 and higher. This engine is recommended to people deploying on windows with IIS.RedisEngine
- Uses redis and php-redis extension to store cache data.
See Cache engine documentation for expected configuration keys.
Property Summary
-
$_config protected static
array
Configuration sets.
-
$_dsnClassMap protected static
array
An array mapping url schemes to fully qualified caching engine class names.
-
$_enabled protected static
bool
Flag for tracking whether or not caching is enabled.
-
$_groups protected static
array
Group to Config mapping
-
$_registry protected static
Cake\Cache\CacheRegistry
Cache Registry used for creating and using cache adapters.
-
$_reset protected static
array
Whether to reset the settings with the next call to Cache::set();
Method Summary
-
_buildEngine() protected static
Finds and builds the instance of the required engine class.
-
clear() public static
Delete all keys from the cache.
-
clearGroup() public static
Delete all keys from the cache belonging to the same group.
-
config() public static
This method can be used to define configuration adapters for an application or read existing configuration.
-
configured() public static
Returns an array containing the named configurations
-
decrement() public static
Decrement a number under the key and return decremented value.
-
delete() public static
Delete a key from the cache.
-
deleteMany() public static
Delete many keys from the cache.
-
disable() public static
Disable caching.
-
drop() public static
Drops a constructed adapter.
-
dsnClassMap() public static
Returns or updates the DSN class map for this class
-
enable() public static
Re-enable caching.
-
enabled() public static
Check whether or not caching is enabled.
-
engine() public static
Fetch the engine attached to a specific configuration name.
-
gc() public static
Garbage collection
-
groupConfigs() public static
Retrieve group names to config mapping.
-
increment() public static
Increment a number under the key and return incremented value.
-
parseDsn() public static
Parses a DSN into a valid connection configuration
-
read() public static
Read a key from the cache.
-
readMany() public static
Read multiple keys from the cache.
-
registry() public static
Returns the Cache Registry instance used for creating and using cache adapters. Also allows for injecting of a new registry instance.
-
remember() public static
Provides the ability to easily do read-through caching.
-
write() public static
Write data for key into cache.
-
writeMany() public static
Write data for many keys into cache.
Method Detail
_buildEngine() ¶ protected static
_buildEngine(string $name): void
Finds and builds the instance of the required engine class.
Parameters
-
string
$name Name of the config array that needs an engine instance built
Returns
void
Throws
InvalidArgumentException
When a cache engine cannot be created.
clear() ¶ public static
clear(bool $check = false, string $config = 'default'): bool
Delete all keys from the cache.
Parameters
-
bool
$check optional if true will check expiration, otherwise delete all
-
string
$config optional name of the configuration to use. Defaults to 'default'
Returns
bool
clearGroup() ¶ public static
clearGroup(string $group, string $config = 'default'): bool
Delete all keys from the cache belonging to the same group.
Parameters
-
string
$group name of the group to be cleared
-
string
$config optional name of the configuration to use. Defaults to 'default'
Returns
bool
config() ¶ public static
config(string|array $key, array $config = null): array|null
This method can be used to define configuration adapters for an application or read existing configuration.
To change an adapter's configuration at runtime, first drop the adapter and then reconfigure it.
Adapters will not be constructed until the first operation is done.
Usage
Assuming that the class' name is Cache
the following scenarios
are supported:
Reading config data back:
Cache::config('default');
Setting a cache engine up.
Cache::config('default', $settings);
Injecting a constructed adapter in:
Cache::config('default', $instance);
Configure multiple adapters at once:
Cache::config($arrayOfConfig);
Parameters
-
string|array
$key The name of the configuration, or an array of multiple configs.
-
array
$config optional An array of name => configuration data for adapter.
Returns
array|null
Throws
BadMethodCallException
When trying to modify an existing config.
configured() ¶ public static
configured(): array
Returns an array containing the named configurations
Returns
array
decrement() ¶ public static
decrement(string $key, int $offset = 1, string $config = 'default'): mixed
Decrement a number under the key and return decremented value.
Parameters
-
string
$key Identifier for the data
-
int
$offset optional How much to subtract
-
string
$config optional Optional string configuration name. Defaults to 'default'
Returns
mixed
delete() ¶ public static
delete(string $key, string $config = 'default'): bool
Delete a key from the cache.
Usage:
Deleting from the active cache configuration.
Cache::delete('my_data');
Deleting from a specific cache configuration.
Cache::delete('my_data', 'long_term');
Parameters
-
string
$key Identifier for the data
-
string
$config optional name of the configuration to use. Defaults to 'default'
Returns
bool
deleteMany() ¶ public static
deleteMany(array $keys, string $config = 'default'): array
Delete many keys from the cache.
Usage:
Deleting multiple keys from the active cache configuration.
Cache::deleteMany(['my_data_1', 'my_data_2']);
Deleting from a specific cache configuration.
Cache::deleteMany(['my_data_1', 'my_data_2], 'long_term');
Parameters
-
array
$keys Array of cache keys to be deleted
-
string
$config optional name of the configuration to use. Defaults to 'default'
Returns
array
disable() ¶ public static
disable(): void
Disable caching.
When disabled all cache operations will return null.
Returns
void
drop() ¶ public static
drop(string $config): bool
Drops a constructed adapter.
If you wish to modify an existing configuration, you should drop it, change configuration and then re-add it.
If the implementing objects supports a $_registry
object the named configuration
will also be unloaded from the registry.
Parameters
-
string
$config An existing configuration you wish to remove.
Returns
bool
dsnClassMap() ¶ public static
dsnClassMap(array|null $map = null): array
Returns or updates the DSN class map for this class
Parameters
-
array|null
$map optional Additions/edits to the class map to apply
Returns
array
enable() ¶ public static
enable(): void
Re-enable caching.
If caching has been disabled with Cache::disable() this method will reverse that effect.
Returns
void
engine() ¶ public static
engine(string $config): Cake\Cache\CacheEngine
Fetch the engine attached to a specific configuration name.
If the cache engine & configuration are missing an error will be triggered.
Parameters
-
string
$config The configuration name you want an engine for.
Returns
Cake\Cache\CacheEngine
gc() ¶ public static
gc(string $config = 'default', int|null $expires = null): void
Garbage collection
Permanently remove all expired and deleted data
Parameters
-
string
$config optional [optional] The config name you wish to have garbage collected. Defaults to 'default'
-
int|null
$expires optional [optional] An expires timestamp. Defaults to NULL
Returns
void
groupConfigs() ¶ public static
groupConfigs(string|null $group = null): array
Retrieve group names to config mapping.
Cache::config('daily', ['duration' => '1 day', 'groups' => ['posts']]);
Cache::config('weekly', ['duration' => '1 week', 'groups' => ['posts', 'archive']]);
$configs = Cache::groupConfigs('posts');
$configs will equal to ['posts' => ['daily', 'weekly']]
Calling this method will load all the configured engines.
Parameters
-
string|null
$group optional group name or null to retrieve all group mappings
Returns
array
Throws
InvalidArgumentException
increment() ¶ public static
increment(string $key, int $offset = 1, string $config = 'default'): mixed
Increment a number under the key and return incremented value.
Parameters
-
string
$key Identifier for the data
-
int
$offset optional How much to add
-
string
$config optional Optional string configuration name. Defaults to 'default'
Returns
mixed
parseDsn() ¶ public static
parseDsn(string $dsn): array
Parses a DSN into a valid connection configuration
This method allows setting a DSN using formatting similar to that used by PEAR::DB. The following is an example of its usage:
$dsn = 'mysql://user:pass@localhost/database?';
$config = ConnectionManager::parseDsn($dsn);
$dsn = 'Cake\Log\Engine\FileLog://?types=notice,info,debug&file=debug&path=LOGS';
$config = Log::parseDsn($dsn);
$dsn = 'smtp://user:secret@localhost:25?timeout=30&client=null&tls=null';
$config = Email::parseDsn($dsn);
$dsn = 'file:///?className=\My\Cache\Engine\FileEngine';
$config = Cache::parseDsn($dsn);
$dsn = 'File://?prefix=myapp_cake_core_&serialize=true&duration=+2 minutes&path=/tmp/persistent/';
$config = Cache::parseDsn($dsn);
For all classes, the value of scheme
is set as the value of both the className
unless they have been otherwise specified.
Note that querystring arguments are also parsed and set as values in the returned configuration.
Parameters
-
string
$dsn The DSN string to convert to a configuration array
Returns
array
Throws
InvalidArgumentException
If not passed a string
read() ¶ public static
read(string $key, string $config = 'default'): mixed
Read a key from the cache.
Usage:
Reading from the active cache configuration.
Cache::read('my_data');
Reading from a specific cache configuration.
Cache::read('my_data', 'long_term');
Parameters
-
string
$key Identifier for the data
-
string
$config optional optional name of the configuration to use. Defaults to 'default'
Returns
mixed
readMany() ¶ public static
readMany(array $keys, string $config = 'default'): array
Read multiple keys from the cache.
Usage:
Reading multiple keys from the active cache configuration.
Cache::readMany(['my_data_1', 'my_data_2]);
Reading from a specific cache configuration.
Cache::readMany(['my_data_1', 'my_data_2], 'long_term');
Parameters
-
array
$keys an array of keys to fetch from the cache
-
string
$config optional optional name of the configuration to use. Defaults to 'default'
Returns
array
registry() ¶ public static
registry(Cake\Core\ObjectRegistry $registry = null): Cake\Core\ObjectRegistry
Returns the Cache Registry instance used for creating and using cache adapters. Also allows for injecting of a new registry instance.
Parameters
-
Cake\Core\ObjectRegistry
$registry optional Injectable registry object.
Returns
Cake\Core\ObjectRegistry
remember() ¶ public static
remember(string $key, callable $callable, string $config = 'default'): mixed
Provides the ability to easily do read-through caching.
When called if the $key is not set in $config, the $callable function will be invoked. The results will then be stored into the cache config at key.
Examples:
Using a Closure to provide data, assume $this
is a Table object:
$results = Cache::remember('all_articles', function () {
return $this->find('all');
});
Parameters
-
string
$key The cache key to read/store data at.
-
callable
$callable The callable that provides data in the case when the cache key is empty. Can be any callable type supported by your PHP.
-
string
$config optional The cache configuration to use for this operation. Defaults to default.
Returns
mixed
write() ¶ public static
write(string $key, mixed $value, string $config = 'default'): bool
Write data for key into cache.
Usage:
Writing to the active cache config:
Cache::write('cached_data', $data);
Writing to a specific cache config:
Cache::write('cached_data', $data, 'long_term');
Parameters
-
string
$key Identifier for the data
-
mixed
$value Data to be cached - anything except a resource
-
string
$config optional Optional string configuration name to write to. Defaults to 'default'
Returns
bool
writeMany() ¶ public static
writeMany(array $data, string $config = 'default'): array
Write data for many keys into cache.
Usage:
Writing to the active cache config:
Cache::writeMany(['cached_data_1' => 'data 1', 'cached_data_2' => 'data 2']);
Writing to a specific cache config:
Cache::writeMany(['cached_data_1' => 'data 1', 'cached_data_2' => 'data 2'], 'long_term');
Parameters
-
array
$data An array of data to be stored in the cache
-
string
$config optional Optional string configuration name to write to. Defaults to 'default'
Returns
array
Throws
RuntimeException
Property Detail
$_dsnClassMap ¶ protected static
An array mapping url schemes to fully qualified caching engine class names.
Type
array
$_registry ¶ protected static
Cache Registry used for creating and using cache adapters.
Type
Cake\Cache\CacheRegistry
$_reset ¶ protected static
Whether to reset the settings with the next call to Cache::set();
Type
array