8
8
The Cache Component
9
9
===================
10
10
11
- The Cache component provides an extended `PSR-6 `_ implementation as well as
12
- a `PSR-16 `_ "Simple Cache" implementation for adding cache to your applications.
13
- It is designed for performance and resiliency, and ships with ready to use
14
- adapters for the most common caching backends, including proxies for adapting
15
- from/to `Doctrine Cache `_.
11
+ The Cache component provides features covering simple to advanced caching needs.
12
+ It natively implements `PSR-6 `_ and the `Cache Contract `_ for greatest
13
+ 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.
16
17
17
18
Installation
18
19
------------
@@ -23,112 +24,133 @@ Installation
23
24
24
25
.. include :: /components/require_autoload.rst.inc
25
26
26
- Cache (PSR-6) Versus Simple Cache (PSR-16)
27
- ------------------------------------------
27
+ .. _cache-psr-6-versus-simple-cache-psr-16 :
28
+
29
+ Cache Contracts versus PSR-6
30
+ ----------------------------
28
31
29
32
This component includes *two * different approaches to caching:
30
33
31
34
:ref: `PSR-6 Caching <cache-component-psr6-caching >`:
32
- A fully-featured cache system, which includes cache "pools", more advanced
33
- cache "items", and :ref: `cache tagging for invalidation <cache-component-tags >`.
35
+ A generic cache system, which involves cache "pools" and cache "items".
36
+
37
+ :ref: `Cache Contracts <cache-component-contracts >`:
38
+ A simple yet powerful way to store, fetch and remove values from a cache.
34
39
35
- :ref: `PSR-16 Simple Caching <cache-component-psr16-caching >`:
36
- A simple way to store, fetch and remove items from a cache.
40
+ .. tip ::
37
41
38
- Both methods support the *same * cache adapters and will give you very similar performance.
42
+ Using the Cache Contracts approach is recommended: using it requires less
43
+ code boilerplate and provides cache stampede protection by default.
39
44
40
45
.. tip ::
41
46
42
- The component also contains adapters to convert between PSR-6 and PSR-16 caches.
43
- See :doc: `/components/cache/psr6_psr16_adapters `.
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 `.
44
50
45
- .. _cache-component-psr16-caching :
51
+ .. _cache-component-contracts :
46
52
47
- Simple Caching (PSR-16)
48
- -----------------------
53
+ Cache Contracts
54
+ ---------------
49
55
50
- This part of the component is an implementation of `PSR-16 `_, which means that its
51
- basic API is the same as defined in the standard. First, create a cache object from
52
- one of the built-in cache classes. For example, to create a filesystem-based cache,
53
- instantiate :class: `Symfony\\ Component\\ Cache\\ Simple\\ FilesystemCache `::
56
+ All adapters supports the Cache Contract. It contains only two methods:
57
+ ``get() `` and ``delete() ``. There's no ``set() `` method because the ``get() ``
58
+ method both gets and sets the cache values.
54
59
55
- use Symfony\Component\Cache\Simple\FilesystemCache;
60
+ The first thing you need is to instantiate a cache adapter. The
61
+ :class: `Symfony\\ Component\\ Cache\\ Simple\\ FilesystemCache ` is used in this
62
+ example::
56
63
57
- $cache = new FilesystemCache() ;
64
+ use Symfony\Component\Cache\Adapter\FilesystemAdapter ;
58
65
59
- Now you can create, retrieve, update and delete items using this object::
66
+ $cache = new FilesystemAdapter();
60
67
61
- // save a new item in the cache
62
- $cache->set('stats.products_count', 4711);
68
+ Now you can retrieve and delete cached data using this object. The first
69
+ argument of the ``get() `` method is a key, an arbitrary string that you
70
+ 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::
63
73
64
- // or set it with a custom ttl
65
- // $cache->set('stats.products_count', 4711, 3600);
74
+ use Symfony\Contracts\Cache\ItemInterface;
66
75
67
- // retrieve the cache item
68
- if (!$cache->has('stats.products_count')) {
69
- // ... item does not exists in the cache
70
- }
76
+ // The callable will only be executed on a cache miss.
77
+ $value = $cache->get('my_cache_key', function (ItemInterface $item) {
78
+ $item->expiresAfter(3600);
71
79
72
- // retrieve the value stored by the item
73
- $productsCount = $cache->get('stats.products_count');
80
+ // ... do some HTTP request or heavy computations
81
+ $computedValue = 'foobar';
82
+
83
+ return $computedValue;
84
+ });
85
+
86
+ echo $value; // 'foobar'
74
87
75
- // or specify a default value, if the key doesn't exist
76
- // $productsCount = $ cache->get('stats.products_count', 100 );
88
+ // ... and to remove the cache key
89
+ $ cache->delete('my_cache_key' );
77
90
78
- // remove the cache key
79
- $cache->delete('stats.products_count');
91
+ .. note ::
80
92
81
- // clear *all* cache keys
82
- $ cache->clear();
93
+ Use cache tags to delete more than one key at the time. Read more at
94
+ :doc: ` /components/ cache/cache_invalidation `.
83
95
84
- You can also work with multiple items at once::
96
+ The Cache Contracts also comes with built in `Stampede prevention `_. This will
97
+ 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
101
+ is computed again. The next second the same thing happens. So the data is computed
102
+ about 50 times before the cache is warm again. This is where you need stampede
103
+ prevention
85
104
86
- $ cache->setMultiple([
87
- 'stats.products_count' => 4711,
88
- 'stats.users_count' => 1356,
89
- ]);
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".
90
109
91
- $stats = $cache->getMultiple([
92
- 'stats.products_count',
93
- 'stats.users_count',
94
- ]);
110
+ 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
112
+ recompute::
95
113
96
- $cache->deleteMultiple([
97
- 'stats.products_count',
98
- 'stats.users_count',
99
- ]);
114
+ use Symfony\Contracts\Cache\ItemInterface;
100
115
101
- Available Simple Cache (PSR-16) Classes
102
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
116
+ $beta = 1.0;
117
+ $value = $cache->get('my_cache_key', function (ItemInterface $item) {
118
+ $item->expiresAfter(3600);
119
+ $item->tag(['tag_0', 'tag_1');
120
+
121
+ return '...';
122
+ }, $beta);
123
+
124
+ Available Cache Adapters
125
+ ~~~~~~~~~~~~~~~~~~~~~~~~
103
126
104
127
The following cache adapters are available:
105
128
106
129
.. tip ::
107
130
108
131
To find out more about each of these classes, you can read the
109
- :doc: `PSR-6 Cache Pool </components/cache/cache_pools >` page. These "Simple"
110
- (PSR-16) cache classes aren't identical to the PSR-6 Adapters on that page, but
111
- each share constructor arguments and use-cases.
112
-
113
- * :class: `Symfony\\ Component\\ Cache\\ Simple\\ ApcuCache `
114
- * :class: `Symfony\\ Component\\ Cache\\ Simple\\ ArrayCache `
115
- * :class: `Symfony\\ Component\\ Cache\\ Simple\\ ChainCache `
116
- * :class: `Symfony\\ Component\\ Cache\\ Simple\\ DoctrineCache `
117
- * :class: `Symfony\\ Component\\ Cache\\ Simple\\ FilesystemCache `
118
- * :class: `Symfony\\ Component\\ Cache\\ Simple\\ MemcachedCache `
119
- * :class: `Symfony\\ Component\\ Cache\\ Simple\\ NullCache `
120
- * :class: `Symfony\\ Component\\ Cache\\ Simple\\ PdoCache `
121
- * :class: `Symfony\\ Component\\ Cache\\ Simple\\ PhpArrayCache `
122
- * :class: `Symfony\\ Component\\ Cache\\ Simple\\ PhpFilesCache `
123
- * :class: `Symfony\\ Component\\ Cache\\ Simple\\ RedisCache `
124
- * :class: `Symfony\\ Component\\ Cache\\ Simple\\ TraceableCache `
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 `
125
147
126
148
.. _cache-component-psr6-caching :
127
149
128
- More Advanced Caching (PSR-6)
129
- -----------------------------
150
+ More Generic Caching (PSR-6)
151
+ ----------------------------
130
152
131
- To use the more-advanced , PSR-6 Caching abilities, you'll need to learn its key
153
+ To use the more-generic , PSR-6 Caching abilities, you'll need to learn its key
132
154
concepts:
133
155
134
156
**Item **
@@ -177,8 +199,10 @@ Now you can create, retrieve, update and delete items using this cache pool::
177
199
178
200
For a list of all of the supported adapters, see :doc: `/components/cache/cache_pools `.
179
201
180
- Advanced Usage (PSR-6)
181
- ----------------------
202
+ .. _advanced-usage-psr-6 :
203
+
204
+ Advanced Usage
205
+ --------------
182
206
183
207
.. toctree ::
184
208
:glob:
@@ -187,5 +211,7 @@ Advanced Usage (PSR-6)
187
211
cache/*
188
212
189
213
.. _`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
190
215
.. _`PSR-16` : http://www.php-fig.org/psr/psr-16/
191
216
.. _Doctrine Cache : https://www.doctrine-project.org/projects/cache.html
217
+ .. _Stampede prevention : https://en.wikipedia.org/wiki/Cache_stampede
0 commit comments