8000 [Cache] Update cache for 4.2 by Nyholm · Pull Request #11391 · symfony/symfony-docs · GitHub
[go: up one dir, main page]

Skip to content

[Cache] Update cache for 4.2 #11391

8000
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 90 additions & 76 deletions components/cache.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
The Cache Component
===================

The Cache component provides an extended `PSR-6`_ implementation as well as
a `PSR-16`_ "Simple Cache" implementation for adding cache to your applications.
It is designed for performance and resiliency, and ships with ready to use
adapters for the most common caching backends, including proxies for adapting
from/to `Doctrine Cache`_.
The Cache component provides features covering simple to advanced caching needs.
It natively implements `PSR-6`_ and the `Cache Contract`_ for greatest
interoperability. It is designed for performance and resiliency, ships with
ready to use adapters for the most common caching backends, including proxies for
adapting from/to `Doctrine Cache`_ and `PSR-16`_. It enables tag-based invalidation
and cache stampede protection.

Installation
------------
Expand All @@ -23,112 +24,121 @@ Installation

.. include:: /components/require_autoload.rst.inc

Cache (PSR-6) Versus Simple Cache (PSR-16)
------------------------------------------
.. _cache-psr-6-versus-simple-cache-psr-16:

Cache Contracts versus PSR-6
----------------------------

This component includes *two* different approaches to caching:

:ref:`PSR-6 Caching <cache-component-psr6-caching>`:
A fully-featured cache system, which includes cache "pools", more advanced
cache "items", and :ref:`cache tagging for invalidation <cache-component-tags>`.
A generic cache system, which involves cache "pools" and cache "items".

:ref:`Cache Contracts <cache-component-contracts>`:
A simple yet powerful way to store, fetch and remove values from a cache.

:ref:`PSR-16 Simple Caching <cache-component-psr16-caching>`:
A simple way to store, fetch and remove items from a cache.
.. tip::

Both methods support the *same* cache adapters and will give you very similar performance.
Using the Cache Contracts approach is recommended: using it requires less
code boilerplate and provides cache stampede protection by default.

.. tip::

The component also contains adapters to convert between PSR-6 and PSR-16 caches.
See :doc:`/components/cache/psr6_psr16_adapters`.
The component also contains adapters to convert between PSR-6, PSR-16 and
Doctrine caches. See :doc:`/components/cache/psr6_psr16_adapters` and
:doc:`/components/cache/adapters/doctrine_adapter`.

.. _cache-component-psr16-caching:
.. _cache-component-contracts:

Simple Caching (PSR-16)
-----------------------
Cache Contracts
---------------

This part of the component is an implementation of `PSR-16`_, which means that its
basic API is the same as defined in the standard. First, create a cache object from
one of the built-in cache classes. For example, to create a filesystem-based cache,
instantiate :class:`Symfony\\Component\\Cache\\Simple\\FilesystemCache`::
All adapters supports the Cache Contract. It contains only two methods; ``get`` and
``delete``. The first thing you need is to instantiate a cache adapter. The
:class:`Symfony\\Component\\Cache\\Simple\\FilesystemCache` is used in this example::

use Symfony\Component\Cache\Simple\FilesystemCache;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

$cache = new FilesystemCache();
$cache = new FilesystemAdapter();

Now you can create, retrieve, update and delete items using this object::
Now you can retrieve and delete cached data using this object::

// save a new item in the cache
$cache->set('stats.products_count', 4711);
use Symfony\Contracts\Cache\ItemInterface;

// or set it with a custom ttl
// $cache->set('stats.products_count', 4711, 3600);
// The callable will only be executed on a cache miss.
$value = $cache->get('my_cache_key', function (ItemInterface $item) {
$item->expiresAfter(3600);

// retrieve the cache item
if (!$cache->has('stats.products_count')) {
// ... item does not exists in the cache
}
// ... do some HTTP request or heavy computations
$computedValue = 'foobar';

// retrieve the value stored by the item
$productsCount = $cache->get('stats.products_count');
return $computedValue;
});

// or specify a default value, if the key doesn't exist
// $productsCount = $cache->get('stats.products_count', 100);
echo $value; // 'foobar'

// remove the cache key
$cache->delete('stats.products_count');
// ... and to remove the cache key
$cache->delete('my_cache_key');

// clear *all* cache keys
$cache->clear();
.. note::

You can also work with multiple items at once::
Use tags to clear more than one key at the time. Read more at
:doc:`/components/cache/cache_invalidation`.

$cache->setMultiple([
'stats.products_count' => 4711,
'stats.users_count' => 1356,
]);
The Cache Contracts also comes with built in `Stampede prevention`_. This will
remove CPU spikes at the moments when the cache is cold. If an example application
spends 5 seconds to compute data that is cached for 1 hour. This data is accessed
10 times every second. This means that you mostly have cache hits and everything
is fine. But after one hour, we get 10 new requests to a cold cache. So the data
is computed again. The next second the same thing happens. So the data is computed
about 50 times before the cache is warm again. This is where you need stampede
prevention

$stats = $cache->getMultiple([
'stats.products_count',
'stats.users_count',
]);
The solution is to recompute the value before the cache expires. The algorithm
randomly fakes a cache miss for one user while others still is served the cached
value. The third parameter to ``CacheInterface::get`` is a beta value. The default
is ``1.0`` which works well in practice. A higher value means earlier recompute.::

$cache->deleteMultiple([
'stats.products_count',
'stats.users_count',
]);
use Symfony\Contracts\Cache\ItemInterface;

Available Simple Cache (PSR-16) Classes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$beta = 1.0;
$value = $cache->get('my_cache_key', function (ItemInterface $item) {
$item->expiresAfter(3600);
$item->tag(['tag_0', 'tag_1');

return '...';
}, $beta);

Available Cache Adapters
~~~~~~~~~~~~~~~~~~~~~~~~

The following cache adapters are available:

.. tip::

To find out more about each of these classes, you can read the
:doc:`PSR-6 Cache Pool </components/cache/cache_pools>` page. These "Simple"
(PSR-16) cache classes aren't identical to the PSR-6 Adapters on that page, but
each share constructor arguments and use-cases.

* :class:`Symfony\\Component\\Cache\\Simple\\ApcuCache`
* :class:`Symfony\\Component\\Cache\\Simple\\ArrayCache`
* :class:`Symfony\\Component\\Cache\\Simple\\ChainCache`
* :class:`Symfony\\Component\\Cache\\Simple\\DoctrineCache`
* :class:`Symfony\\Component\\Cache\\Simple\\FilesystemCache`
* :class:`Symfony\\Component\\Cache\\Simple\\MemcachedCache`
* :class:`Symfony\\Component\\Cache\\Simple\\NullCache`
* :class:`Symfony\\Component\\Cache\\Simple\\PdoCache`
* :class:`Symfony\\Component\\Cache\\Simple\\PhpArrayCache`
* :class:`Symfony\\Component\\Cache\\Simple\\PhpFilesCache`
* :class:`Symfony\\Component\\Cache\\Simple\\RedisCache`
* :class:`Symfony\\Component\\Cache\\Simple\\TraceableCache`
:doc:`PSR-6 Cache Pool </components/cache/cache_pools>` page.

* :class:`Symfony\\Component\\Cache\\Adapter\\ApcuAdapter`
* :class:`Symfony\\Component\\Cache\\Adapter\\ArrayAdapter`
* :class:`Symfony\\Component\\Cache\\Adapter\\ChainAdapter`
* :class:`Symfony\\Component\\Cache\\Adapter\\DoctrineAdapter`
* :class:`Symfony\\Component\\Cache\\Adapter\\FilesystemAdapter`
* :class:`Symfony\\Component\\Cache\\Adapter\\MemcachedAdapter`
* :class:`Symfony\\Component\\Cache\\Adapter\\NullAdapter`
* :class:`Symfony\\Component\\Cache\\Adapter\\PdoAdapter`
* :class:`Symfony\\Component\\Cache\\Adapter\\PhpArrayAdapter`
* :class:`Symfony\\Component\\Cache\\Adapter\\PhpFilesAdapter`
* :class:`Symfony\\Component\\Cache\\Adapter\\RedisAdapter`
* :class:`Symfony\\Component\\Cache\\Adapter\\SimpleCacheAdapter`
* :class:`Symfony\\Component\\Cache\\Adapter\\TraceableAdapter`

.. _cache-component-psr6-caching:

More Advanced Caching (PSR-6)
-----------------------------
More Generic Caching (PSR-6)
----------------------------

To use the more-advanced, PSR-6 Caching abilities, you'll need to learn its key
To use the more-generic, PSR-6 Caching abilities, you'll need to learn its key
concepts:

**Item**
Expand Down Expand Up @@ -177,8 +187,10 @@ Now you can create, retrieve, update and delete items using this cache pool::

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

Advanced Usage (PSR-6)
----------------------
.. _advanced-usage-psr-6:

Advanced Usage
--------------

.. toctree::
:glob:
Expand All @@ -187,5 +199,7 @@ Advanced Usage (PSR-6)
cache/*

.. _`PSR-6`: http://www.php-fig.org/psr/psr-6/
.. _`Cache Contract`: https://github.com/symfony/contracts/blob/v1.0.0/Cache/CacheInterface.php
.. _`PSR-16`: http://www.php-fig.org/psr/psr-16/
.. _Doctrine Cache: https://www.doctrine-project.org/projects/cache.html
.. _Stampede prevention: https://en.wikipedia.org/wiki/Cache_stampede
4 changes: 3 additions & 1 deletion components/cache/psr6_psr16_adapters.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
Adapters For Interoperability between PSR-6 and PSR-16 Cache
============================================================

Sometimes, you may have a Cache object that implements the :ref:`PSR-16 <cache-component-psr16-caching>`
Sometimes, you may have a Cache object that implements the `PSR-16`_
standard, but need to pass it to an object that expects a :ref:`PSR-6 <cache-component-psr6-caching>`
cache adapter. Or, you might have the opposite situation. The cache component contains
two classes for bidirectional interoperability between PSR-6 and PSR-16 caches.
Expand Down Expand Up @@ -84,3 +84,5 @@ this use-case::

// now use this wherever you want
$githubApiClient = new GitHubApiClient($psr16Cache);

.. _`PSR-16`: http://www.php-fig.org/psr/psr-16/
0