The Cache Component

3.2 version

The Cache Component

The Cache component provides an extended PSR-6 implementation for adding cache to your applications. It is designed to have a low overhead and it ships with ready to use adapters for the most common caching backends.

3.1The Cache component was introduced in Symfony 3.1.

Installation

You can install the component in 2 different ways:

Key Concepts

Before starting to use the Cache component, it's important that you learn the meaning of some 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, etc.)

Basic Usage

This 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
$numProducts = $cache->getItem('stats.num_products');

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

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

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

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