New in Symfony 3.3: Simple Cache

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.

Contributed by
Nicolas Grekas
in #20694.

In Symfony 3.1, we added a new Cache component that implemented the PSR-6: Caching Interface standard. In Symfony 3.2 we improved the component with tagged caches and other improvements.

Although the Cache component provides everything that enterprise applications need, for smaller applications it's a bit cumbersome to use. For example, to use a file system based cache to store, fetch and delete a simple variable, you must do the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

$cache = new FilesystemAdapter();

// save an item in the cache
$numProducts = $cache->getItem('stats.num_products');
$numProducts->set(4711);
$cache->save($numProducts);

// fetch the item from the cache
$numProducts = $cache->getItem('stats.num_products');
if (!$numProducts->isHit()) {
    // ... item does not exist in the cache
} else {
    $total = $numProducts->get();
}

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

In Symfony 3.3 we decided to improve the Cache component by implementing a related standard called PSR-16: Common Interface for Caching Libraries. In short, it's a simplified cache mechanism to store, fetch and remove items from a cache. This is how the previous example would look with the new cache:

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

$cache = new FilesystemCache();

// save an item in the cache
$cache->set('stats.num_products', 4711);

// fetch the item from the cache
if (!$cache->has('stats.num_products')) {
    // ... item does not exist in the cache
} else {
    $total = $cache->get('stats.num_products');
}

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

The simple cache also allows to define default values when items don't exist in the cache and it defines the setMultiple(), getMultiple() and deleteMultiple() methods to work with several items simultaneously.

Both the regular cache and the simple cache support the same cache adapters (file system, Redis, Memcache, etc.) and both provide similar performance, so the decision to choose one or another should be based on the features that you'll need for the cache.

Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.

Comments

Great ! Former Cache API was confusing.

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.