You are browsing the Symfony 4 documentation, which changes significantly from Symfony 3.x. If your app doesn't use Symfony 4 yet, browse the Symfony 3.4 documentation.

The Cache Component

4.2 version
Maintained Unmaintained

The Cache Component

The Cache component provides features covering simple to advanced caching needs. It natively implements PSR-6 and the Cache Contract for greatest interoperability. It is designed for performance and resiliency, ships with ready to use adapters for the most common caching backends, including proxies for adapting from/to Doctrine Cache and PSR-16. It enables tag-based invalidation and cache stampede protection.

Installation

1
$ composer require symfony/cache

Note

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

Cache Contracts versus PSR-6

This component includes two different approaches to caching:

PSR-6 Caching:
A generic cache system, which involves cache "pools" and cache "items".
Cache Contracts:
A simple yet powerful way to store, fetch and remove values from a cache.

Tip

Using the Cache Contracts approach is recommended: using it requires less code boilerplate and provides cache stampede protection by default.

Tip

The component also contains adapters to convert between PSR-6, PSR-16 and Doctrine caches. See Adapters For Interoperability between PSR-6 and PSR-16 Cache and Doctrine Cache Adapter.

Cache Contracts

All adapters supports the Cache Contract. It contains only two methods: get() and delete(). There's no set() method because the get() method both gets and sets the cache values.

The first thing you need is to instantiate a cache adapter. The FilesystemCache is used in this example:

use Symfony\Component\Cache\Adapter\FilesystemAdapter;

$cache = new FilesystemAdapter();

Now you can retrieve and delete cached data using this object. The first argument of the get() method is a key, an arbitrary string that you associate to the cached value so you can retrieve it later. The second argument is a PHP callable which is executed to generate the value (and store it in the cache) when it's not found in the cache:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
use Symfony\Contracts\Cache\ItemInterface;

// The callable will only be executed on a cache miss.
$value = $cache->get('my_cache_key', function (ItemInterface $item) {
    $item->expiresAfter(3600);

    // ... do some HTTP request or heavy computations
    $computedValue = 'foobar';

    return $computedValue;
});

echo $value; // 'foobar'

// ... and to remove the cache key
$cache->delete('my_cache_key');

Note

Use cache tags to delete more than one key at the time. Read more at Cache Invalidation.

The Cache Contracts also comes with built in Stampede prevention. This will remove CPU spikes at the moments when the cache is cold. If an example application spends 5 seconds to compute data that is cached for 1 hour. This data is accessed 10 times every second. This means that you mostly have cache hits and everything is fine. But after one hour, we get 10 new requests to a cold cache. So the data is computed again. The next second the same thing happens. So the data is computed about 50 times before the cache is warm again. This is where you need stampede prevention

The solution is to recompute the value before the cache expires. The algorithm randomly fakes a cache miss for one user while others still is served the cached value. You can control its behavior with the third optional parameter of CacheInterface::get(), which is a float value called "beta".

By default the beta is 1.0 and higher values mean earlier recompute. Set it to 0 to disable the recompute and set it to INF to trigger an immediate recompute:

1
2
3
4
5
6
7
8
9
use Symfony\Contracts\Cache\ItemInterface;

$beta = 1.0;
$value = $cache->get('my_cache_key', function (ItemInterface $item) {
    $item->expiresAfter(3600);
    $item->tag(['tag_0', 'tag_1']);

    return '...';
}, $beta);

Available Cache Adapters

The following cache adapters are available:

Tip

To find out more about each of these classes, you can read the PSR-6 Cache Pool page.

More Generic Caching (PSR-6)

To use the more-generic, PSR-6 Caching abilities, you'll need to learn its key concepts:

Item
A single unit of information stored as a key/value pair, where the key is the unique identifier of the information and the value is its contents;
Pool
A logical repository of cache items. All cache operations (saving items, looking for items, etc.) are performed through the pool. Applications can define as many pools as needed.
Adapter
It implements the actual caching mechanism to store the information in the filesystem, in a database, etc. The component provides several ready to use adapters for common caching backends (Redis, APCu, Doctrine, PDO, etc.)

Basic Usage (PSR-6)

This part of the component is an implementation of PSR-6, which means that its basic API is the same as defined in the standard. Before starting to cache information, create the cache pool using any of the built-in adapters. For example, to create a filesystem-based cache, instantiate FilesystemAdapter:

use Symfony\Component\Cache\Adapter\FilesystemAdapter;

$cache = new FilesystemAdapter();

Now you can create, retrieve, update and delete items using this cache pool:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// create a new item by trying to get it from the cache
$productsCount = $cache->getItem('stats.products_count');

// assign a value to the item and save it
$productsCount->set(4711);
$cache->save($productsCount);

// retrieve the cache item
$productsCount = $cache->getItem('stats.products_count');
if (!$productsCount->isHit()) {
    // ... item does not exists in the cache
}
// retrieve the value stored by the item
$total = $productsCount->get();

// remove the cache item
$cache->deleteItem('stats.products_count');

For a list of all of the supported adapters, see Cache Pools and Supported Adapters.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.