Fr3nch13/CakePHP Utilities

Cache
in package
uses StaticConfigTrait

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\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.

Tags
see

config/app.php for configuration settings

Table of Contents

Properties

$_config  : array<string, mixed>
Configuration sets.
$_dsnClassMap  : array<string, string>
An array mapping URL schemes to fully qualified caching engine class names.
$_enabled  : bool
Flag for tracking whether caching is enabled.
$_groups  : array<string, array<string|int, mixed>>
Group to Config mapping
$_registry  : CacheRegistry|null
Cache Registry used for creating and using cache adapters.

Methods

add()  : bool
Write data for key into a cache engine if it doesn't exist already.
clear()  : bool
Delete all keys from the cache.
clearAll()  : array<string, bool>
Delete all keys from the cache from all configurations.
clearGroup()  : bool
Delete all keys from the cache belonging to the same group.
configured()  : array<string|int, string>
Returns an array containing the named configurations
decrement()  : int|false
Decrement a number under the key and return decremented value.
delete()  : bool
Delete a key from the cache.
deleteMany()  : bool
Delete many keys from the cache.
disable()  : void
Disable caching.
drop()  : bool
Drops a constructed adapter.
enable()  : void
Re-enable caching.
enabled()  : bool
Check whether caching is enabled.
engine()  : CacheInterface|CacheEngineInterface
Get a cache engine object for the named cache config.
getConfig()  : mixed|null
Reads existing configuration.
getConfigOrFail()  : mixed
Reads existing configuration for a specific key.
getDsnClassMap()  : array<string, string>
Returns the DSN class map for this class.
getRegistry()  : CacheRegistry
Returns the Cache Registry instance used for creating and using cache adapters.
groupConfigs()  : array<string, array<string|int, mixed>>
Retrieve group names to config mapping.
increment()  : int|false
Increment a number under the key and return incremented value.
parseDsn()  : array<string, mixed>
Parses a DSN into a valid connection configuration
pool()  : CacheInterface|CacheEngineInterface
Get a SimpleCacheEngine object for the named cache pool.
read()  : mixed
Read a key from the cache.
readMany()  : iterable<string|int, mixed>
Read multiple keys from the cache.
remember()  : mixed
Provides the ability to easily do read-through caching.
setConfig()  : void
This method can be used to define configuration adapters for an application.
setDsnClassMap()  : void
Updates the DSN class map for this class.
setRegistry()  : void
Sets the Cache Registry instance used for creating and using cache adapters.
write()  : bool
Write data for key into cache.
writeMany()  : bool
Write data for many keys into cache.
_buildEngine()  : void
Finds and builds the instance of the required engine class.

Properties

$_config

Configuration sets.

protected static array<string, mixed> $_config = []

$_dsnClassMap

An array mapping URL schemes to fully qualified caching engine class names.

protected static array<string, string> $_dsnClassMap = ['array' => \Cake\Cache\Engine\ArrayEngine::class, 'apcu' => \Cake\Cache\Engine\ApcuEngine::class, 'file' => \Cake\Cache\Engine\FileEngine::class, 'memcached' => \Cake\Cache\Engine\MemcachedEngine::class, 'null' => \Cake\Cache\Engine\NullEngine::class, 'redis' => \Cake\Cache\Engine\RedisEngine::class, 'wincache' => \Cake\Cache\Engine\WincacheEngine::class]
Tags
psalm-var

array<string, class-string>

$_enabled

Flag for tracking whether caching is enabled.

protected static bool $_enabled = true

$_groups

Group to Config mapping

protected static array<string, array<string|int, mixed>> $_groups = []

$_registry

Cache Registry used for creating and using cache adapters.

protected static CacheRegistry|null $_registry

Methods

add()

Write data for key into a cache engine if it doesn't exist already.

public static add(string $key, mixed $value[, string $config = 'default' ]) : bool

Usage:

Writing to the active cache config:

Cache::add('cached_data', $data);

Writing to a specific cache config:

Cache::add('cached_data', $data, 'long_term');
Parameters
$key : string

Identifier for the data.

$value : mixed

Data to be cached - anything except a resource.

$config : string = 'default'

Optional string configuration name to write to. Defaults to 'default'.

Return values
bool

True if the data was successfully cached, false on failure. Or if the key existed already.

clear()

Delete all keys from the cache.

public static clear([string $config = 'default' ]) : bool
Parameters
$config : string = 'default'

name of the configuration to use. Defaults to 'default'

Return values
bool

True if the cache was successfully cleared, false otherwise

clearAll()

Delete all keys from the cache from all configurations.

public static clearAll() : array<string, bool>
Return values
array<string, bool>

Status code. For each configuration, it reports the status of the operation

clearGroup()

Delete all keys from the cache belonging to the same group.

public static clearGroup(string $group[, string $config = 'default' ]) : bool
Parameters
$group : string

name of the group to be cleared

$config : string = 'default'

name of the configuration to use. Defaults to 'default'

Return values
bool

True if the cache group was successfully cleared, false otherwise

configured()

Returns an array containing the named configurations

public static configured() : array<string|int, string>
Return values
array<string|int, string>

Array of configurations.

decrement()

Decrement a number under the key and return decremented value.

public static decrement(string $key[, int $offset = 1 ][, string $config = 'default' ]) : int|false
Parameters
$key : string

Identifier for the data

$offset : int = 1

How much to subtract

$config : string = 'default'

Optional string configuration name. Defaults to 'default'

Tags
throws
InvalidArgumentException

when offset < 0

Return values
int|false

New value, or false if the data doesn't exist, is not integer, or if there was an error fetching it

delete()

Delete a key from the cache.

public static delete(string $key[, string $config = 'default' ]) : bool

Usage:

Deleting from the active cache configuration.

Cache::delete('my_data');

Deleting from a specific cache configuration.

Cache::delete('my_data', 'long_term');
Parameters
$key : string

Identifier for the data

$config : string = 'default'

name of the configuration to use. Defaults to 'default'

Return values
bool

True if the value was successfully deleted, false if it didn't exist or couldn't be removed

deleteMany()

Delete many keys from the cache.

public static deleteMany(iterable<string|int, mixed> $keys[, string $config = 'default' ]) : bool

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
$keys : iterable<string|int, mixed>

Array or Traversable of cache keys to be deleted

$config : string = 'default'

name of the configuration to use. Defaults to 'default'

Tags
throws
InvalidArgumentException
Return values
bool

True on success, false on failure.

disable()

Disable caching.

public static disable() : void

When disabled all cache operations will return null.

drop()

Drops a constructed adapter.

public static drop(string $config) : bool

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
$config : string

An existing configuration you wish to remove.

Return values
bool

Success of the removal, returns false when the config does not exist.

enable()

Re-enable caching.

public static enable() : void

If caching has been disabled with Cache::disable() this method will reverse that effect.

enabled()

Check whether caching is enabled.

public static enabled() : bool
Return values
bool

getConfig()

Reads existing configuration.

public static getConfig(string $key) : mixed|null
Parameters
$key : string

The name of the configuration.

Return values
mixed|null

Configuration data at the named key or null if the key does not exist.

getConfigOrFail()

Reads existing configuration for a specific key.

public static getConfigOrFail(string $key) : mixed

The config value for this key must exist, it can never be null.

Parameters
$key : string

The name of the configuration.

Tags
throws
InvalidArgumentException

If value does not exist.

Return values
mixed

Configuration data at the named key.

getDsnClassMap()

Returns the DSN class map for this class.

public static getDsnClassMap() : array<string, string>
Tags
psalm-return

array<string, class-string>

Return values
array<string, string>

getRegistry()

Returns the Cache Registry instance used for creating and using cache adapters.

public static getRegistry() : CacheRegistry
Return values
CacheRegistry

groupConfigs()

Retrieve group names to config mapping.

public static groupConfigs([string|null $group = null ]) : array<string, array<string|int, mixed>>
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
$group : string|null = null

Group name or null to retrieve all group mappings

Tags
throws
InvalidArgumentException
Return values
array<string, array<string|int, mixed>>

Map of group and all configuration that has the same group

increment()

Increment a number under the key and return incremented value.

public static increment(string $key[, int $offset = 1 ][, string $config = 'default' ]) : int|false
Parameters
$key : string

Identifier for the data

$offset : int = 1

How much to add

$config : string = 'default'

Optional string configuration name. Defaults to 'default'

Tags
throws
InvalidArgumentException

When offset < 0

Return values
int|false

New value, or false if the data doesn't exist, is not integer, or if there was an error fetching it.

parseDsn()

Parses a DSN into a valid connection configuration

public static parseDsn(string $dsn) : array<string, mixed>

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
$dsn : string

The DSN string to convert to a configuration array

Tags
throws
InvalidArgumentException

If not passed a string, or passed an invalid string

Return values
array<string, mixed>

The configuration array to be stored after parsing the DSN

read()

Read a key from the cache.

public static read(string $key[, string $config = 'default' ]) : mixed

Usage:

Reading from the active cache configuration.

Cache::read('my_data');

Reading from a specific cache configuration.

Cache::read('my_data', 'long_term');
Parameters
$key : string

Identifier for the data

$config : string = 'default'

optional name of the configuration to use. Defaults to 'default'

Return values
mixed

The cached data, or null if the data doesn't exist, has expired, or if there was an error fetching it.

readMany()

Read multiple keys from the cache.

public static readMany(iterable<string|int, mixed> $keys[, string $config = 'default' ]) : iterable<string|int, mixed>

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
$keys : iterable<string|int, mixed>

An array or Traversable of keys to fetch from the cache

$config : string = 'default'

optional name of the configuration to use. Defaults to 'default'

Tags
throws
InvalidArgumentException
Return values
iterable<string|int, mixed>

An array containing, for each of the given $keys, the cached data or false if cached data could not be retrieved.

remember()

Provides the ability to easily do read-through caching.

public static remember(string $key, callable $callable[, string $config = 'default' ]) : mixed

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();
});
Parameters
$key : string

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.

$config : string = 'default'

The cache configuration to use for this operation. Defaults to default.

Return values
mixed

If the key is found: the cached data. If the key is not found the value returned by the callable.

setConfig()

This method can be used to define configuration adapters for an application.

public static setConfig(array<string, mixed>|string $key[, mixed $config = null ]) : void

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:

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);
Parameters
$key : array<string, mixed>|string

The name of the configuration, or an array of multiple configs.

$config : mixed = null

Configuration value. Generally an array of name => configuration data for adapter.

Tags
throws
BadMethodCallException

When trying to modify an existing config.

throws
LogicException

When trying to store an invalid structured config array.

setDsnClassMap()

Updates the DSN class map for this class.

public static setDsnClassMap(array<string, string> $map) : void
Parameters
$map : array<string, string>

Additions/edits to the class map to apply.

Tags
psalm-param

array<string, class-string> $map

setRegistry()

Sets the Cache Registry instance used for creating and using cache adapters.

public static setRegistry(CacheRegistry $registry) : void

Also allows for injecting of a new registry instance.

Parameters
$registry : CacheRegistry

Injectable registry object.

write()

Write data for key into cache.

public static write(string $key, mixed $value[, string $config = 'default' ]) : bool

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
$key : string

Identifier for the data

$value : mixed

Data to be cached - anything except a resource

$config : string = 'default'

Optional string configuration name to write to. Defaults to 'default'

Return values
bool

True if the data was successfully cached, false on failure

writeMany()

Write data for many keys into cache.

public static writeMany(iterable<string|int, mixed> $data[, string $config = 'default' ]) : bool

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
$data : iterable<string|int, mixed>

An array or Traversable of data to be stored in the cache

$config : string = 'default'

Optional string configuration name to write to. Defaults to 'default'

Tags
throws
InvalidArgumentException
Return values
bool

True on success, false on failure

_buildEngine()

Finds and builds the instance of the required engine class.

protected static _buildEngine(string $name) : void
Parameters
$name : string

Name of the config array that needs an engine instance built

Tags
throws
InvalidArgumentException

When a cache engine cannot be created.

throws
RuntimeException

If loading of the engine failed.


        
On this page

Search results