Quantcast
Channel: Symfony Blog
Viewing all articles
Browse latest Browse all 3098

New in Symfony 3.3: Simple Cache

$
0
0
Nicolas Grekas

Contributed by
Nicolas Grekas
in #20694.

In Symfony 3.1, we added a new Cache component that implemented thePSR-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
useSymfony\Component\Cache\Adapter\FilesystemAdapter;$cache=newFilesystemAdapter();// 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
useSymfony\Component\Cache\Simple\FilesystemCache;$cache=newFilesystemCache();// save an item in the cache$cache->set('stats.num_products',4711);// fetch the item from the cacheif(!$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.


Be trained by Symfony experts - 2017-02-06 Paris - 2017-02-06 Paris - 2017-02-08 Paris

Viewing all articles
Browse latest Browse all 3098

Latest Images

Trending Articles



Latest Images