Skip to content

Commit 57c5910

Browse files
Update Cache component doc for 4.2
1 parent f83b88a commit 57c5910

11 files changed

+143
-91
lines changed

components/cache.rst

Lines changed: 40 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,16 @@ The Cache Component
99
===================
1010

1111
The Cache component provides features covering simple to advanced caching needs.
12-
It natively implements `PSR-6`_ and the `Cache Contract`_ for greatest
12+
It natively implements `PSR-6`_ and the `Cache Contracts`_ for greatest
1313
interoperability. It is designed for performance and resiliency, ships with
14-
ready to use adapters for the most common caching backends, including proxies for
15-
adapting from/to `Doctrine Cache`_ and `PSR-16`_. It enables tag-based invalidation
16-
and cache stampede protection.
14+
ready to use adapters for the most common caching backends. It enables tag-based
15+
invalidation and cache stampede protection via locking and early expiration.
16+
17+
.. tip::
18+
19+
The component also contains adapters to convert between PSR-6, PSR-16 and
20+
Doctrine caches. See :doc:`/components/cache/psr6_psr16_adapters` and
21+
:doc:`/components/cache/adapters/doctrine_adapter`.
1722

1823
Installation
1924
------------
@@ -24,8 +29,6 @@ Installation
2429
2530
.. include:: /components/require_autoload.rst.inc
2631

27-
.. _cache-psr-6-versus-simple-cache-psr-16:
28-
2932
Cache Contracts versus PSR-6
3033
----------------------------
3134

@@ -35,25 +38,19 @@ This component includes *two* different approaches to caching:
3538
A generic cache system, which involves cache "pools" and cache "items".
3639

3740
:ref:`Cache Contracts <cache-component-contracts>`:
38-
A simple yet powerful way to store, fetch and remove values from a cache.
41+
A simpler yet more powerful way to cache values based on recomputation callbacks.
3942

4043
.. tip::
4144

42-
Using the Cache Contracts approach is recommended: using it requires less
45+
Using the Cache Contracts approach is recommended: it requires less
4346
code boilerplate and provides cache stampede protection by default.
4447

45-
.. tip::
46-
47-
The component also contains adapters to convert between PSR-6, PSR-16 and
48-
Doctrine caches. See :doc:`/components/cache/psr6_psr16_adapters` and
49-
:doc:`/components/cache/adapters/doctrine_adapter`.
50-
5148
.. _cache-component-contracts:
5249

5350
Cache Contracts
5451
---------------
5552

56-
All adapters supports the Cache Contract. It contains only two methods:
53+
All adapters supports the Cache Contracts. It contains only two methods:
5754
``get()`` and ``delete()``. There's no ``set()`` method because the ``get()``
5855
method both gets and sets the cache values.
5956

@@ -68,8 +65,8 @@ example::
6865
Now you can retrieve and delete cached data using this object. The first
6966
argument of the ``get()`` method is a key, an arbitrary string that you
7067
associate to the cached value so you can retrieve it later. The second argument
71-
is a PHP callable which is executed to generate the value (and store it in the
72-
cache) when it's not found in the cache::
68+
is a PHP callable which is executed when the key is not found in the cache to
69+
generate and return the value::
7370

7471
use Symfony\Contracts\Cache\ItemInterface;
7572

@@ -95,20 +92,27 @@ cache) when it's not found in the cache::
9592

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

105-
The solution is to recompute the value before the cache expires. The algorithm
106-
randomly fakes a cache miss for one user while others still is served the cached
107-
value. You can control its behavior with the third optional parameter of
108-
``CacheInterface::get()``, which is a float value called "beta".
102+
The first solution that is locking: on a per-host basis, only one PHP process is
103+
allowed to compute a specific key at a time. Locking is built in by default in so
104+
that you don't have anything specific to do other than leveraging the Cache
105+
Contracts.
106+
107+
The second solution is also built in when using the Cache Contracts: instead of
108+
waiting for the full delay before expiring a value, it is recomputed ahead of its
109+
expiration date: the `Probabilistic early expiration`_ algorithm randomly fakes a
110+
cache miss for one user while others still are served the cached value. You can
111+
control its behavior with the third optional parameter of ``CacheInterface::get()``,
112+
which is a float value called "beta".
109113

110114
By default the beta is ``1.0`` and higher values mean earlier recompute. Set it
111-
to ``0`` to disable the recompute and set it to ``INF`` to trigger an immediate
115+
to ``0`` to disable early recompute and set it to ``INF`` to force an immediate
112116
recompute::
113117

114118
use Symfony\Contracts\Cache\ItemInterface;
@@ -126,36 +130,24 @@ Available Cache Adapters
126130

127131
The following cache adapters are available:
128132

129-
.. tip::
133+
.. toctree::
134+
:glob:
135+
:maxdepth: 1
130136

131-
To find out more about each of these classes, you can read the
132-
:doc:`PSR-6 Cache Pool </components/cache/cache_pools>` page.
133-
134-
* :class:`Symfony\\Component\\Cache\\Adapter\\ApcuAdapter`
135-
* :class:`Symfony\\Component\\Cache\\Adapter\\ArrayAdapter`
136-
* :class:`Symfony\\Component\\Cache\\Adapter\\ChainAdapter`
137-
* :class:`Symfony\\Component\\Cache\\Adapter\\DoctrineAdapter`
138-
* :class:`Symfony\\Component\\Cache\\Adapter\\FilesystemAdapter`
139-
* :class:`Symfony\\Component\\Cache\\Adapter\\MemcachedAdapter`
140-
* :class:`Symfony\\Component\\Cache\\Adapter\\NullAdapter`
141-
* :class:`Symfony\\Component\\Cache\\Adapter\\PdoAdapter`
142-
* :class:`Symfony\\Component\\Cache\\Adapter\\PhpArrayAdapter`
143-
* :class:`Symfony\\Component\\Cache\\Adapter\\PhpFilesAdapter`
144-
* :class:`Symfony\\Component\\Cache\\Adapter\\RedisAdapter`
145-
* :class:`Symfony\\Component\\Cache\\Adapter\\SimpleCacheAdapter`
146-
* :class:`Symfony\\Component\\Cache\\Adapter\\TraceableAdapter`
137+
adapters/*
147138

148139
.. _cache-component-psr6-caching:
149140

150-
More Generic Caching (PSR-6)
151-
----------------------------
141+
Generic Caching (PSR-6)
142+
-----------------------
152143

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

156147
**Item**
157148
A single unit of information stored as a key/value pair, where the key is
158149
the unique identifier of the information and the value is its contents;
150+
see the :doc:`/components/cache/cache_items` article for more details.
159151
**Pool**
160152
A logical repository of cache items. All cache operations (saving items,
161153
looking for items, etc.) are performed through the pool. Applications can
@@ -169,7 +161,7 @@ Basic Usage (PSR-6)
169161
-------------------
170162

171163
This part of the component is an implementation of `PSR-6`_, which means that its
172-
basic API is the same as defined in the standard. Before starting to cache information,
164+
basic API is the same as defined in the document. Before starting to cache information,
173165
create the cache pool using any of the built-in adapters. For example, to create
174166
a filesystem-based cache, instantiate :class:`Symfony\\Component\\Cache\\Adapter\\FilesystemAdapter`::
175167

@@ -199,8 +191,6 @@ Now you can create, retrieve, update and delete items using this cache pool::
199191

200192
For a list of all of the supported adapters, see :doc:`/components/cache/cache_pools`.
201193

202-
.. _advanced-usage-psr-6:
203-
204194
Advanced Usage
205195
--------------
206196

@@ -211,7 +201,8 @@ Advanced Usage
211201
cache/*
212202

213203
.. _`PSR-6`: http://www.php-fig.org/psr/psr-6/
214-
.. _`Cache Contract`: https://github.com/symfony/contracts/blob/v1.0.0/Cache/CacheInterface.php
204+
.. _`Cache Contracts`: https://github.com/symfony/contracts/blob/master/Cache/CacheInterface.php
215205
.. _`PSR-16`: http://www.php-fig.org/psr/psr-16/
216206
.. _Doctrine Cache: https://www.doctrine-project.org/projects/cache.html
217207
.. _Stampede prevention: https://en.wikipedia.org/wiki/Cache_stampede
208+
.. _Probabilistic early expiration: https://en.wikipedia.org/wiki/Cache_stampede#Probabilistic_early_expiration

components/cache/adapters/apcu_adapter.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
.. index::
22
single: Cache Pool
3-
single: APC Cache, APCu Cache
3+
single: APCu Cache
44

55
.. _apcu-adapter:
66

components/cache/adapters/doctrine_adapter.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,9 @@ third parameters::
3434
$defaultLifetime = 0
3535
);
3636

37+
.. tip::
38+
39+
A :class:`Symfony\\Component\\Cache\\DoctrineProvider` class is also provided by the
40+
component to use any PSR6-compatible implementations with Doctrine-compatible classes.
41+
3742
.. _`Doctrine Cache`: https://github.com/doctrine/cache

components/cache/adapters/php_array_cache_adapter.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ Php Array Cache Adapter
66
=======================
77

88
This adapter is a high performance cache for static data (e.g. application configuration)
9-
that is optimized and preloaded into OPcache memory storage::
9+
that is optimized and preloaded into OPcache memory storage. It is suited for any data that
10+
is mostly read-only after warmup::
1011

1112
use Symfony\Component\Cache\Adapter\PhpArrayAdapter;
1213
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
@@ -34,5 +35,4 @@ that is optimized and preloaded into OPcache memory storage::
3435

3536
.. note::
3637

37-
This adapter requires PHP 7.x and should be used with the php.ini setting
38-
``opcache.enable`` on.
38+
This adapter requires turning on the ``opcache.enable`` php.ini setting.

components/cache/adapters/php_files_adapter.rst

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,15 +29,16 @@ file similar to the following::
2929

3030
.. note::
3131

32+
This adapter requires turning on the ``opcache.enable`` php.ini setting.
3233
As cache items are included and parsed as native PHP code and due to the way `OPcache`_
3334
handles file includes, this adapter has the potential to be much faster than other
3435
filesystem-based caches.
3536

3637
.. caution::
3738

38-
If you have configured OPcache to
39-
:ref:`not check the file timestamps <performance-dont-check-timestamps>`
40-
the cached items will not not be invalidated unless you clear OPcache.
39+
While it supports updates and because it is using OPcache as a backend, this adapter is
40+
better suited for append-mostly needs. Using it other scenarios might lead to periodical
41+
reset of the OPcache memory, potentially leading to degreaded performance.
4142

4243
The PhpFilesAdapter can optionally be provided a namespace, default cache lifetime, and cache
4344
directory path as constructor arguments::

components/cache/adapters/proxy_adapter.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ This adapter wraps a `PSR-6`_ compliant `cache item pool interface`_. It is used
99
your application's cache item pool implementation with the Symfony :ref:`Cache Component <cache-component>`
1010
by consuming any implementation of ``Psr\Cache\CacheItemPoolInterface``.
1111

12+
It can also be used to prefix all keys automatically before storing items in the decorated pool,
13+
effectively allowing the creation of several namespaced pools out of a single one.
14+
1215
This adapter expects a ``Psr\Cache\CacheItemPoolInterface`` instance as its first parameter,
1316
and optionally a namespace and default cache lifetime as its second and third parameters::
1417

components/cache/adapters/redis_adapter.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
Redis Cache Adapter
88
===================
99

10-
This adapter stores the values in-memory using one (or more) `Redis server`_ instances.
10+
This adapter stores the values in-memory using one (or more) `Redis server`_ instances.
1111
Unlike the :ref:`APCu adapter <apcu-adapter>`, and similarly to the
1212
:ref:`Memcached adapter <memcached-adapter>`, it is not limited to the current server's
1313
shared memory; you can store contents independent of your PHP environment. The ability

components/cache/cache_invalidation.rst

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ several cached items, keeping them in sync can be difficult.
1313
The Symfony Cache component provides two mechanisms to help solving this problem:
1414

1515
* :ref:`Tags-based invalidation <cache-component-tags>` for managing data dependencies;
16-
* :ref:`Expiration based invalidation <cache-component-expiration>` for time related dependencies.
16+
* :ref:`Expiration based invalidation <cache-component-expiration>` for time-related dependencies.
1717

1818
.. _cache-component-tags:
1919

@@ -25,28 +25,27 @@ each cached item. Each tag is a plain string identifier that you can use at any
2525
time to trigger the removal of all items associated with this tag.
2626

2727
To attach tags to cached items, you need to use the
28-
:method:`Symfony\\Component\\Cache\\CacheItem::tag` method that is implemented by
29-
cache items, as returned by cache adapters::
28+
:method:`Symfony\Contracts\Cache\\ItemInterface::tag` method that is implemented by
29+
cache items::
3030

31-
$item = $cache->getItem('cache_key');
32-
// ...
33-
// add one or more tags
34-
$item->tag('tag_1');
35-
$item->tag(['tag_2', 'tag_3']);
36-
$cache->save($item);
31+
$item = $cache->get('cache_key', function (ItemInterface $item) {
32+
// [...]
33+
// add one or more tags
34+
$item->tag('tag_1');
35+
$item->tag(['tag_2', 'tag_3']);
3736

38-
If ``$cache`` implements :class:`Symfony\\Component\\Cache\\Adapter\\TagAwareAdapterInterface`,
37+
return $cachedValue;
38+
});
39+
40+
If ``$cache`` implements :class:`Symfony\\Contracts\\Cache\\TagAwareCacheInterface`,
3941
you can invalidate the cached items by calling
40-
:method:`Symfony\\Component\\Cache\\Adapter\\TagAwareAdapterInterface::invalidateTags`::
42+
:method:`Symfony\\Contracts\\Cache\\TagAwareCacheInterface::invalidateTags`::
4143

4244
// invalidate all items related to `tag_1` or `tag_3`
4345
$cache->invalidateTags(['tag_1', 'tag_3']);
4446

4547
// if you know the cache key, you can also delete the item directly
46-
$cache->deleteItem('cache_key');
47-
48-
// If you don't remember the item key, you can use the getKey() method
49-
$cache->deleteItem($item->getKey());
48+
$cache->delete('cache_key');
5049

5150
Using tags invalidation is very useful when tracking cache keys becomes difficult.
5251

@@ -55,7 +54,7 @@ Tag Aware Adapters
5554

5655
To store tags, you need to wrap a cache adapter with the
5756
:class:`Symfony\\Component\\Cache\\Adapter\\TagAwareAdapter` class or implement
58-
:class:`Symfony\\Component\\Cache\\Adapter\\TagAwareAdapterInterface` and its only
57+
:class:`Symfony\\Contracts\\Cache\\TagAwareCacheInterface` and its
5958
:method:`Symfony\\Component\\Cache\\Adapter\\TagAwareAdapterInterface::invalidateTags`
6059
method.
6160

components/cache/cache_items.rst

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Cache Items
99
Cache items are the information units stored in the cache as a key/value pair.
1010
In the Cache component they are represented by the
1111
:class:`Symfony\\Component\\Cache\\CacheItem` class.
12+
They are used in both the Cache Contracts and the PSR-6 interfaces.
1213

1314
Cache Item Keys and Values
1415
--------------------------
@@ -27,14 +28,22 @@ arrays and objects.
2728
Creating Cache Items
2829
--------------------
2930

30-
Cache items are created with the ``getItem($key)`` method of the cache pool. The
31-
argument is the key of the item::
31+
The only way to create cache items is via cache pools. When using the Cache
32+
Contracts, they are passed as arguments to the recomputation callback::
33+
34+
// $cache pool object was created before
35+
$productsCount = $cache->get('stats.products_count', function (ItemInterface $item) {
36+
// [...]
37+
});
38+
39+
When using PSR-6, they are created with the ``getItem($key)`` method of the cache
40+
pool::
3241

3342
// $cache pool object was created before
3443
$productsCount = $cache->getItem('stats.products_count');
3544

36-
Then, use the ``Psr\\Cache\\CacheItemInterface::set`` method to set
37-
the data stored in the cache item::
45+
Then, use the ``Psr\\Cache\\CacheItemInterface::set`` method to set the data stored
46+
in the cache item (this step is done automatically when using the Cache Contracts)::
3847

3948
// storing a simple integer
4049
$productsCount->set(4711);
@@ -67,7 +76,6 @@ lifespan. Consider for example an application which caches the latest news just
6776
for one minute. In those cases, use the ``expiresAfter()`` method to set the
6877
number of seconds to cache the item::
6978

70-
$latestNews = $cache->getItem('latest_news');
7179
$latestNews->expiresAfter(60); // 60 seconds = 1 minute
7280

7381
// this method also accepts \DateInterval instances
@@ -76,23 +84,22 @@ number of seconds to cache the item::
7684
Cache items define another related method called ``expiresAt()`` to set the
7785
exact date and time when the item will expire::
7886

79-
$mostPopularNews = $cache->getItem('popular_news');
8087
$mostPopularNews->expiresAt(new \DateTime('tomorrow'));
8188

8289
Cache Item Hits and Misses
8390
--------------------------
8491

8592
Using a cache mechanism is important to improve the application performance, but
86-
it should not be required to make the application work. In fact, the PSR-6
87-
standard states that caching errors should not result in application failures.
93+
it should not be required to make the application work. In fact, the PSR-6 document
94+
wisely states that caching errors should not result in application failures.
8895

89-
In practice this means that the ``getItem()`` method always returns an object
90-
which implements the ``Psr\Cache\CacheItemInterface`` interface, even when the
91-
cache item doesn't exist. Therefore, you don't have to deal with ``null`` return
96+
In practice with PSR-6, this means that the ``getItem()`` method always returns an
97+
object which implements the ``Psr\Cache\CacheItemInterface`` interface, even when
98+
the cache item doesn't exist. Therefore, you don't have to deal with ``null`` return
9299
values and you can safely store in the cache values such as ``false`` and ``null``.
93100

94-
In order to decide if the returned object is correct or not, caches use the
95-
concept of hits and misses:
101+
In order to decide if the returned object represents a value coming from the storage
102+
or not, caches use the concept of hits and misses:
96103

97104
* **Cache Hits** occur when the requested item is found in the cache, its value
98105
is not corrupted or invalid and it hasn't expired;

0 commit comments

Comments
 (0)