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.
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\ApcuEngine::class, 'prefix' => 'my_app_' ]);
This would configure an APCu 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 7 built-in caching engines:
ApcuEngine
- Uses the APCu object cache, one of the fastest caching engines.ArrayEngine
- Uses only memory to store all data, not actually a persistent engine. Can be useful in test or CLI environment.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.MemcacheEngine
- Uses the PECL::Memcache extension and Memcached for storage. Fast reads/writes, and benefits from memcache being distributed.RedisEngine
- Uses redis and php-redis extension to store cache data.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.XcacheEngine
- Uses the Xcache extension, an alternative to APCu.See Cache engine documentation for expected configuration keys.
array<string, mixed>
Configuration sets.
array<string, string>
An array mapping URL schemes to fully qualified caching engine class names.
bool
Flag for tracking whether caching is enabled.
array<string, array>
Group to Config mapping
Cake\Cache\CacheRegistry|null
Cache Registry used for creating and using cache adapters.
Finds and builds the instance of the required engine class.
Write data for key into a cache engine if it doesn't exist already.
Delete all keys from the cache.
Delete all keys from the cache from all configurations.
Delete all keys from the cache belonging to the same group.
Returns an array containing the named configurations
Decrement a number under the key and return decremented value.
Delete a key from the cache.
Delete many keys from the cache.
Disable caching.
Drops a constructed adapter.
Re-enable caching.
Check whether caching is enabled.
Get a cache engine object for the named cache config.
Reads existing configuration.
Reads existing configuration for a specific key.
Returns the DSN class map for this class.
Returns the Cache Registry instance used for creating and using cache adapters.
Retrieve group names to config mapping.
Increment a number under the key and return incremented value.
Parses a DSN into a valid connection configuration
Get a SimpleCacheEngine object for the named cache pool.
Read a key from the cache.
Read multiple keys from the cache.
Provides the ability to easily do read-through caching.
This method can be used to define configuration adapters for an application.
Updates the DSN class map for this class.
Sets the Cache Registry instance used for creating and using cache adapters.
Write data for key into cache.
Write data for many keys into cache.
_buildEngine(string $name): void
Finds and builds the instance of the required engine class.
string
$name Name of the config array that needs an engine instance built
void
Cake\Cache\InvalidArgumentException
RuntimeException
add(string $key, mixed $value, string $config = 'default'): bool
Write data for key into a cache engine if it doesn't exist already.
Writing to the active cache config:
Cache::add('cached_data', $data);
Writing to a specific cache config:
Cache::add('cached_data', $data, 'long_term');
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'.
bool
clear(string $config = 'default'): bool
Delete all keys from the cache.
string
$config optional name of the configuration to use. Defaults to 'default'
bool
clearAll(): array<string, bool>
Delete all keys from the cache from all configurations.
array<string, bool>
clearGroup(string $group, string $config = 'default'): bool
Delete all keys from the cache belonging to the same group.
string
$group name of the group to be cleared
string
$config optional name of the configuration to use. Defaults to 'default'
bool
configured(): array<string>
Returns an array containing the named configurations
array<string>
decrement(string $key, int $offset = 1, string $config = 'default'): int|false
Decrement a number under the key and return decremented value.
string
$key Identifier for the data
int
$offset optional How much to subtract
string
$config optional Optional string configuration name. Defaults to 'default'
int|false
Cake\Cache\InvalidArgumentException
delete(string $key, string $config = 'default'): bool
Delete a key from the cache.
Deleting from the active cache configuration.
Cache::delete('my_data');
Deleting from a specific cache configuration.
Cache::delete('my_data', 'long_term');
string
$key Identifier for the data
string
$config optional name of the configuration to use. Defaults to 'default'
bool
deleteMany(iterable $keys, string $config = 'default'): bool
Delete many keys from the cache.
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');
iterable
$keys Array or Traversable of cache keys to be deleted
string
$config optional name of the configuration to use. Defaults to 'default'
bool
Cake\Cache\InvalidArgumentException
disable(): void
Disable caching.
When disabled all cache operations will return null.
void
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.
string
$config An existing configuration you wish to remove.
bool
enable(): void
Re-enable caching.
If caching has been disabled with Cache::disable() this method will reverse that effect.
void
enabled(): bool
Check whether caching is enabled.
bool
engine(string $config): Psr\SimpleCache\CacheInterfaceCake\Cache\CacheEngineInterface
Get a cache engine object for the named cache config.
string
$config The name of the configured cache backend.
Psr\SimpleCache\CacheInterfaceCake\Cache\CacheEngineInterface
getConfig(string $key): mixed|null
Reads existing configuration.
string
$key The name of the configuration.
mixed|null
getConfigOrFail(string $key): mixed
Reads existing configuration for a specific key.
The config value for this key must exist, it can never be null.
string
$key The name of the configuration.
mixed
InvalidArgumentException
getDsnClassMap(): array<string, string>
Returns the DSN class map for this class.
array<string, string>
getRegistry(): Cake\Cache\CacheRegistry
Returns the Cache Registry instance used for creating and using cache adapters.
Cake\Cache\CacheRegistry
groupConfigs(string|null $group = null): array<string, 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.
string|null
$group optional Group name or null to retrieve all group mappings
array<string, array>
Cake\Cache\InvalidArgumentException
increment(string $key, int $offset = 1, string $config = 'default'): int|false
Increment a number under the key and return incremented value.
string
$key Identifier for the data
int
$offset optional How much to add
string
$config optional Optional string configuration name. Defaults to 'default'
int|false
Cake\Cache\InvalidArgumentException
parseDsn(string $dsn): array<string, mixed>
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.
string
$dsn The DSN string to convert to a configuration array
array<string, mixed>
InvalidArgumentException
pool(string $config): Psr\SimpleCache\CacheInterfaceCake\Cache\CacheEngineInterface
Get a SimpleCacheEngine object for the named cache pool.
string
$config The name of the configured cache backend.
Psr\SimpleCache\CacheInterfaceCake\Cache\CacheEngineInterface
read(string $key, string $config = 'default'): mixed
Read a key from the cache.
Reading from the active cache configuration.
Cache::read('my_data');
Reading from a specific cache configuration.
Cache::read('my_data', 'long_term');
string
$key Identifier for the data
string
$config optional optional name of the configuration to use. Defaults to 'default'
mixed
readMany(iterable $keys, string $config = 'default'): iterable
Read multiple keys from the cache.
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');
iterable
$keys An array or Traversable of keys to fetch from the cache
string
$config optional optional name of the configuration to use. Defaults to 'default'
iterable
Cake\Cache\InvalidArgumentException
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')->toArray(); });
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.
mixed
setConfig(array<string, mixed>|string $key, object|array<string, mixed>|null $config = null): void
This method can be used to define configuration adapters for an application.
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.
Assuming that the class' name is Cache
the following scenarios are supported:
Setting a cache engine up.
Cache::setConfig('default', $settings);
Injecting a constructed adapter in:
Cache::setConfig('default', $instance);
Configure multiple adapters at once:
Cache::setConfig($arrayOfConfig);
array<string, mixed>|string
$key The name of the configuration, or an array of multiple configs.
object|array<string, mixed>|null
$config optional An array of name => configuration data for adapter.
void
BadMethodCallException
LogicException
setDsnClassMap(array<string, string> $map): void
Updates the DSN class map for this class.
array<string, string>
$map Additions/edits to the class map to apply.
void
setRegistry(Cake\Cache\CacheRegistry $registry): void
Sets the Cache Registry instance used for creating and using cache adapters.
Also allows for injecting of a new registry instance.
Cake\Cache\CacheRegistry
$registry Injectable registry object.
void
write(string $key, mixed $value, string $config = 'default'): bool
Write data for key into cache.
Writing to the active cache config:
Cache::write('cached_data', $data);
Writing to a specific cache config:
Cache::write('cached_data', $data, 'long_term');
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'
bool
writeMany(iterable $data, string $config = 'default'): bool
Write data for many keys into cache.
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');
iterable
$data An array or Traversable of data to be stored in the cache
string
$config optional Optional string configuration name to write to. Defaults to 'default'
bool
Cake\Cache\InvalidArgumentException
Configuration sets.
array<string, mixed>
An array mapping URL schemes to fully qualified caching engine class names.
array<string, string>
Flag for tracking whether caching is enabled.
bool
Group to Config mapping
array<string, array>
Cache Registry used for creating and using cache adapters.
Cake\Cache\CacheRegistry|null
© 2005–present The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/4.4/class-Cake.Cache.Cache.html