CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Team
    • Issues (Github)
    • YouTube Channel
    • Get Involved
    • Bakery
    • Featured Resources
    • Newsletter
    • Certification
    • My CakePHP
    • CakeFest
    • Facebook
    • Twitter
    • Help & Support
    • Forum
    • Stack Overflow
    • IRC
    • Slack
    • Paid Support
CakePHP

C CakePHP 3.8 Red Velvet API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 3.8
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Namespaces

  • Cake
    • Auth
      • Storage
    • Cache
      • Engine
    • Collection
      • Iterator
    • Command
    • Console
      • Exception
    • Controller
      • Component
      • Exception
    • Core
      • Configure
        • Engine
      • Exception
      • Retry
    • Database
      • Driver
      • Exception
      • Expression
      • Schema
      • Statement
      • Type
    • Datasource
      • Exception
    • Error
      • Middleware
    • Event
      • Decorator
    • Filesystem
    • Form
    • Http
      • Client
        • Adapter
        • Auth
      • Cookie
      • Exception
      • Middleware
      • Session
    • I18n
      • Formatter
      • Middleware
      • Parser
    • Log
      • Engine
    • Mailer
      • Exception
      • Transport
    • Network
      • Exception
    • ORM
      • Association
      • Behavior
        • Translate
      • Exception
      • Locator
      • Rule
    • Routing
      • Exception
      • Filter
      • Middleware
      • Route
    • Shell
      • Helper
      • Task
    • TestSuite
      • Fixture
      • Stub
    • Utility
      • Exception
    • Validation
    • View
      • Exception
      • Form
      • Helper
      • Widget
  • None

Classes

  • Cache
  • CacheEngine
  • CacheRegistry
  • SimpleCacheEngine

Interfaces

  • CacheEngineInterface

Exceptions

  • InvalidArgumentException

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\ApcuEngine',
   '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.

Cake\Cache\Cache uses Cake\Core\StaticConfigTrait
Namespace: Cake\Cache
See: config/app.php for configuration settings
Location: Cache/Cache.php

Properties summary

  • $_dsnClassMap protected static
    array

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

  • $_enabled protected static
    boolean
    Flag for tracking whether or not caching is enabled.
  • $_groups protected static
    array
    Group to Config mapping
  • $_registry protected static
    Cake\Core\ObjectRegistry
    Cache Registry used for creating and using cache adapters.

Inherited Properties

  • _config

Method Summary

  • _buildEngine() protected static
    Finds and builds the instance of the required engine class.
  • add() public static
    Write data for key into a cache engine if it doesn't exist already.
  • clear() public static
    Delete all keys from the cache.
  • clearAll() public static
    Delete all keys from the cache from all configurations.
  • clearGroup() public static
    Delete all keys from the cache belonging to the same group.
  • 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.
  • enable() public static
    Re-enable caching.
  • enabled() public static
    Check whether or not caching is enabled.
  • engine() public static deprecated
    Fetch the engine attached to a specific configuration name.
  • gc() public static deprecated
    Garbage collection
  • getRegistry() public static
    Returns the Cache Registry instance used for creating and using cache adapters.
  • groupConfigs() public static
    Retrieve group names to config mapping.
  • increment() public static
    Increment a number under the key and return incremented value.
  • pool() public static
    Get a SimpleCacheEngine object for the named cache pool.
  • read() public static
    Read a key from the cache.
  • readMany() public static
    Read multiple keys from the cache.
  • registry() public static deprecated

    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.
  • setRegistry() public static
    Sets the Cache Registry instance used for creating and using cache adapters.
  • 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 )

Finds and builds the instance of the required engine class.

Parameters
string $name
Name of the config array that needs an engine instance built
Throws
InvalidArgumentException
When a cache engine cannot be created.

add() public static ¶

add( string $key , mixed $value , string $config = 'default' )

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

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
string $key
Identifier for the data.
mixed $value
Data to be cached - anything except a resource.
string $config optional 'default'
Optional string configuration name to write to. Defaults to 'default'.
Returns
boolean

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


clear() public static ¶

clear( boolean $check = false , string $config = 'default' )

Delete all keys from the cache.

Parameters
boolean $check optional false

if true will check expiration, otherwise delete all. This parameter will become a no-op value in 4.0 as it is deprecated.

string $config optional 'default'
name of the configuration to use. Defaults to 'default'
Returns
boolean
True if the cache was successfully cleared, false otherwise

clearAll() public static ¶

clearAll( boolean $check = false )

Delete all keys from the cache from all configurations.

Parameters
boolean $check optional false

if true will check expiration, otherwise delete all. This parameter will become a no-op value in 4.0 as it is deprecated.

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

clearGroup() public static ¶

clearGroup( string $group , string $config = 'default' )

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

Parameters
string $group
name of the group to be cleared
string $config optional 'default'
name of the configuration to use. Defaults to 'default'
Returns
boolean
True if the cache group was successfully cleared, false otherwise

decrement() public static ¶

decrement( string $key , integer $offset = 1 , string $config = 'default' )

Decrement a number under the key and return decremented value.

Parameters
string $key
Identifier for the data
integer $offset optional 1
How much to subtract
string $config optional 'default'
Optional string configuration name. Defaults to 'default'
Returns
integer|false

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


delete() public static ¶

delete( string $key , string $config = 'default' )

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 'default'
name of the configuration to use. Defaults to 'default'
Returns
boolean
True if the value was successfully deleted, false if it didn't exist or couldn't be removed

deleteMany() public static ¶

deleteMany( array $keys , string $config = 'default' )

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 'default'
name of the configuration to use. Defaults to 'default'
Returns
array

of boolean values that are true if the value was successfully deleted, false if it didn't exist or couldn't be removed.


disable() public static ¶

disable( )

Disable caching.

When disabled all cache operations will return null.

enable() public static ¶

enable( )

Re-enable caching.

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

enabled() public static ¶

enabled( )

Check whether or not caching is enabled.

Returns
boolean

engine() public static deprecated ¶

engine( string $config )

Fetch the engine attached to a specific configuration name.

If the cache engine & configuration are missing an error will be triggered.

Deprecated

3.7.0 Use Cache::pool() instead. In 4.0 all cache engines will implement the PSR16 interface and this method does not return objects implementing that interface.


Parameters
string $config
The configuration name you want an engine for.
Returns
Cake\Cache\CacheEngine
When caching is disabled a null engine will be returned.

gc() public static deprecated ¶

gc( string $config = 'default' , integer|null $expires = null )

Garbage collection

Permanently remove all expired and deleted data

Deprecated
3.7.0 Will be removed in 4.0
Parameters
string $config optional 'default'
[optional] The config name you wish to have garbage collected. Defaults to 'default'
integer|null $expires optional null
[optional] An expires timestamp. Defaults to NULL

getRegistry() public static ¶

getRegistry( )

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

Returns
Cake\Core\ObjectRegistry

groupConfigs() public static ¶

groupConfigs( string|null $group = null )

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 null
group name or null to retrieve all group mappings
Returns
array
map of group and all configuration that has the same group
Throws
InvalidArgumentException

increment() public static ¶

increment( string $key , integer $offset = 1 , string $config = 'default' )

Increment a number under the key and return incremented value.

Parameters
string $key
Identifier for the data
integer $offset optional 1
How much to add
string $config optional 'default'
Optional string configuration name. Defaults to 'default'
Returns
integer|false

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


pool() public static ¶

pool( string $config )

Get a SimpleCacheEngine object for the named cache pool.

Parameters
string $config
The name of the configured cache backend.
Returns
Cake\Cache\SimpleCacheEngine

read() public static ¶

read( string $key , string $config = 'default' )

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 'default'
optional name of the configuration to use. Defaults to 'default'
Returns
mixed
The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it

readMany() public static ¶

readMany( array $keys , string $config = 'default' )

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 'default'
optional name of the configuration to use. Defaults to 'default'
Returns
array

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


registry() public static deprecated ¶

registry( Cake\Core\ObjectRegistry $registry = null )

Returns the Cache Registry instance used for creating and using cache adapters. Also allows for injecting of a new registry instance.

Deprecated
Deprecated since 3.5. Use getRegistry() and setRegistry() instead.
Parameters
Cake\Core\ObjectRegistry $registry optional null
Injectable registry object.
Returns
Cake\Core\ObjectRegistry

remember() public static ¶

remember( string $key , callable $callable , string $config = 'default' )

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 'default'

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

Returns
mixed

If the key is found: the cached data, false if the data missing/expired, or an error. If the key is not found: boolean of the success of the write


setRegistry() public static ¶

setRegistry( Cake\Core\ObjectRegistry $registry )

Sets 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
Injectable registry object.

write() public static ¶

write( string $key , mixed $value , string $config = 'default' )

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 'default'
Optional string configuration name to write to. Defaults to 'default'
Returns
boolean
True if the data was successfully cached, false on failure

writeMany() public static ¶

writeMany( array $data , string $config = 'default' )

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 'default'
Optional string configuration name to write to. Defaults to 'default'
Returns
array
of bools for each key provided, indicating true for success or false for fail
Throws
RuntimeException

Methods used from Cake\Core\StaticConfigTrait

config() public static deprecated ¶

config( string|array $key , array|null $config = 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);
Deprecated
3.4.0 Use setConfig()/getConfig() instead.
Parameters
string|array $key
The name of the configuration, or an array of multiple configs.
array|null $config optional null
An array of name => configuration data for adapter.
Returns
array|null
Null when adding configuration or an array of configuration data when reading.
Throws
BadMethodCallException
When trying to modify an existing config.

configured() public static ¶

configured( )

Returns an array containing the named configurations

Returns
string[]
Array of configurations.

drop() public static ¶

drop( string $config )

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
boolean
Success of the removal, returns false when the config does not exist.

dsnClassMap() public static deprecated ¶

dsnClassMap( array $map = null )

Returns or updates the DSN class map for this class.

Deprecated
3.4.0 Use setDsnClassMap()/getDsnClassMap() instead.
Parameters
array $map optional null
Additions/edits to the class map to apply.
Returns
array

getConfig() public static ¶

getConfig( string $key )

Reads existing configuration.

Parameters
string $key
The name of the configuration.
Returns
mixed
Configuration data at the named key or null if the key does not exist.

getDsnClassMap() public static ¶

getDsnClassMap( )

Returns the DSN class map for this class.

Returns
array

parseDsn() public static ¶

parseDsn( string $dsn )

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
The configuration array to be stored after parsing the DSN
Throws
InvalidArgumentException
If not passed a string, or passed an invalid string

setConfig() public static ¶

setConfig( string|array $key , array $config = null )

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.

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
string|array $key
The name of the configuration, or an array of multiple configs.
array $config optional null
An array of name => configuration data for adapter.
Throws
BadMethodCallException
When trying to modify an existing config.
LogicException
When trying to store an invalid structured config array.

setDsnClassMap() public static ¶

setDsnClassMap( array $map )

Updates the DSN class map for this class.

Parameters
array $map
Additions/edits to the class map to apply.

Properties detail

$_dsnClassMap ¶

protected static array

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

[
    'array' => 'Cake\Cache\Engine\ArrayEngine',
    'apc' => 'Cake\Cache\Engine\ApcuEngine', // @deprecated Since 3.6. Use apcu instead.
    'apcu' => 'Cake\Cache\Engine\ApcuEngine',
    'file' => 'Cake\Cache\Engine\FileEngine',
    'memcached' => 'Cake\Cache\Engine\MemcachedEngine',
    'null' => 'Cake\Cache\Engine\NullEngine',
    'redis' => 'Cake\Cache\Engine\RedisEngine',
    'wincache' => 'Cake\Cache\Engine\WincacheEngine',
    'xcache' => 'Cake\Cache\Engine\XcacheEngine',
]

$_enabled ¶

protected static boolean

Flag for tracking whether or not caching is enabled.

true

$_groups ¶

protected static array

Group to Config mapping

[]

$_registry ¶

protected static Cake\Core\ObjectRegistry

Cache Registry used for creating and using cache adapters.

Follow @CakePHP
#IRC
OpenHub
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Logos & Trademarks
  • Community
  • Team
  • Issues (Github)
  • YouTube Channel
  • Get Involved
  • Bakery
  • Featured Resources
  • Newsletter
  • Certification
  • My CakePHP
  • CakeFest
  • Facebook
  • Twitter
  • Help & Support
  • Forum
  • Stack Overflow
  • IRC
  • Slack
  • Paid Support

Generated using CakePHP API Docs