diff --git a/components/cache.rst b/components/cache.rst index 2bb5e60bd8b..8f1394e37d6 100644 --- a/components/cache.rst +++ b/components/cache.rst @@ -3,6 +3,8 @@ single: Performance single: Components; Cache +.. _`cache-component`: + The Cache Component =================== diff --git a/components/cache/adapters/apcu_adapter.rst b/components/cache/adapters/apcu_adapter.rst new file mode 100644 index 00000000000..e064b6c9814 --- /dev/null +++ b/components/cache/adapters/apcu_adapter.rst @@ -0,0 +1,54 @@ +.. index:: + single: Cache Pool + single: APC Cache, APCu Cache + +.. _apcu-adapter: + +APCu Cache Adapter +================== + +This adapter is a high-performance, shared memory cache. It can increase the +application performance very significantly because the cache contents are +stored in the shared memory of your server, a component that is much faster than +others, such as the filesystem. + +.. caution:: + + **Requirement:** The `APCu extension`_ must be installed and active to use + this adapter. + +This adapter can be provided an optional namespace string as its first parameter, a +default cache lifetime as its second parameter, and a version string as its third +parameter:: + + use Symfony\Component\Cache\Adapter\ApcuAdapter; + + $cache = new ApcuAdapter( + + // a string prefixed to the keys of the items stored in this cache + $namespace = '', + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until the APCu memory is cleared) + $defaultLifetime = 0, + + // when set, all keys prefixed by $namespace can be invalidated by changing + // this $version string + $version = null + ); + +.. caution:: + + It is *not* recommended to use this adapter when performing a large number of + write and delete operations, as these operations result in fragmentation of the + APCu memory, resulting in *significantly* degraded performance. + +.. tip:: + + Note that this adapter's CRUD operations are specific to the PHP SAPI it is running + under. This means adding a cache item using the CLI will not result in the item + appearing under FPM. Likewise, deletion of an item using CGI will not result in the + item being deleted under the CLI. + +.. _`APCu extension`: https://pecl.php.net/package/APCu \ No newline at end of file diff --git a/components/cache/adapters/array_cache_adapter.rst b/components/cache/adapters/array_cache_adapter.rst new file mode 100644 index 00000000000..ffdc1d60dd0 --- /dev/null +++ b/components/cache/adapters/array_cache_adapter.rst @@ -0,0 +1,27 @@ +.. index:: + single: Cache Pool + single: Array Cache + +Array Cache Adapter +=================== + +Generally, this adapter is useful for testing purposes, as its contents are stored in memory +and not persisted outside the running PHP process in any way. It can also be useful while +warming up caches, due to the :method:`Symfony\\Component\\Cache\\Adapter\\ArrayAdapter::getValues` +method. + +This adapter can be passed a default cache lifetime as its first parameter, and a boolean that +toggles serialization as its second parameter:: + + use Symfony\Component\Cache\Adapter\ArrayAdapter; + + $cache = new ArrayAdapter( + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until the current PHP process finishes) + $defaultLifetime = 0, + + // if ``true``, the values saved in the cache are serialized before storing them + $storeSerialized = true + ); diff --git a/components/cache/adapters/chain_adapter.rst b/components/cache/adapters/chain_adapter.rst new file mode 100644 index 00000000000..f3d5cfc0253 --- /dev/null +++ b/components/cache/adapters/chain_adapter.rst @@ -0,0 +1,43 @@ +.. index:: + single: Cache Pool + single: Chain Cache + +Chain Cache Adapter +=================== + +This adapter allows to combine any number of the other available cache adapters. +Cache items are fetched from the first adapter which contains them and cache items are +saved in all the given adapters. This offers a simple way of creating a layered cache. + +This adapter expects an array of adapters as its first parameter, and optionally a +maximum cache lifetime as its second parameter:: + + use Symfony\Component\Cache\Adapter\ApcuAdapter; + + $cache = new ChainAdapter(array( + + // The ordered list of adapters used to fetch cached items + array $adapters, + + // The max lifetime of items propagated from lower adapters to upper ones + $maxLifetime = 0 + )); + +.. note:: + + When an item is not found in the first adapter but is found in the next ones, this + adapter ensures that the fetched item is saved in all the adapters where it was + previously missing. + +The following example shows how to create a chain adapter instance using the fastest and +slowest storage engines, :class:`Symfony\\Component\\Cache\\Adapter\\ApcuAdapter` and +:class:`Symfony\\Component\\Cache\\Adapter\\FilesystemAdapter`, respectfully:: + + use Symfony\Component\Cache\Adapter\ApcuAdapter; + use Symfony\Component\Cache\Adapter\ChainAdapter; + use Symfony\Component\Cache\Adapter\FilesystemAdapter; + + $cache = new ChainAdapter(array( + new ApcuAdapter(), + new FilesystemAdapter(), + )); diff --git a/components/cache/adapters/doctrine_adapter.rst b/components/cache/adapters/doctrine_adapter.rst new file mode 100644 index 00000000000..5ceefa950de --- /dev/null +++ b/components/cache/adapters/doctrine_adapter.rst @@ -0,0 +1,37 @@ +.. index:: + single: Cache Pool + single: Doctrine Cache + +.. _`doctrine-adapter`: + +Doctrine Cache Adapter +====================== + +This adapter wraps any class extending the `Doctrine Cache`_ abstract provider, allowing +you to use these providers in your application as if they were Symfony Cache adapters. + +This adapter expects a ``\Doctrine\Common\Cache\CacheProvider`` instance as its first +parameter, and optionally a namespace and default cache lifetime as its second and +third parameters:: + + use Doctrine\Common\Cache\CacheProvider; + use Doctrine\Common\Cache\SQLite3Cache; + use Symfony\Component\Cache\Adapter\DoctrineAdapter; + + $provider = new SQLite3Cache(new \SQLite3(__DIR__.'/cache/data.sqlite'), 'youTableName'); + + $symfonyCache = new DoctrineAdapter( + + // a cache provider instance + CacheProvider $provider, + + // a string prefixed to the keys of the items stored in this cache + $namespace = '', + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until the database table is truncated or its rows are otherwise deleted) + $defaultLifetime = 0 + ); + +.. _`Doctrine Cache`: https://github.com/doctrine/cache diff --git a/components/cache/adapters/filesystem_adapter.rst b/components/cache/adapters/filesystem_adapter.rst new file mode 100644 index 00000000000..5c8177199aa --- /dev/null +++ b/components/cache/adapters/filesystem_adapter.rst @@ -0,0 +1,38 @@ +.. index:: + single: Cache Pool + single: Filesystem Cache + +Filesystem Cache Adapter +======================== + +This adapter is useful when you want to improve the application performance but +can't install tools like APCu or Redis on the server. This adapter stores the +contents as regular files in a set of directories on the local file system. + +This adapter can optionally be provided a namespace, default cache lifetime, and +directory path, as its first, second, and third parameters:: + + use Symfony\Component\Cache\Adapter\FilesystemAdapter; + + $cache = new FilesystemAdapter( + + // a string used as the subdirectory of the root cache directory, where cache + // items will be stored + $namespace = '', + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until the files are deleted) + $defaultLifetime = 0, + + // the main cache directory (the application needs read-write permissions on it) + // if none is specified, a directory is created inside the system temporary directory + $directory = null + ); + +.. tip:: + + This adapter is generally the *slowest* due to the overhead of file IO. If throughput is paramount, + the in-memory adapters (such as :ref:`APCu `, :ref:`Memcached `, + and :ref:`Redis `) or the database adapters (such as + :ref:`Doctrine ` and :ref:`PDO & Doctrine `) are recommended. diff --git a/components/cache/adapters/memcached_adapter.rst b/components/cache/adapters/memcached_adapter.rst new file mode 100644 index 00000000000..413db7d89fa --- /dev/null +++ b/components/cache/adapters/memcached_adapter.rst @@ -0,0 +1,294 @@ +.. index:: + single: Cache Pool + single: Memcached Cache + +.. _memcached-adapter: + +Memcached Cache Adapter +======================= + +.. versionadded:: 3.3 + + The Memcached adapter was introduced in Symfony 3.3. + +This adapter stores the values in-memory using one (or more) `Memcached server`_ +instances. Unlike the :ref:`APCu adapter `, and similarly to the +:ref:`Redis adapter `, it is not limited to the current server's +shared memory; you can store contents independent of your PHP environment. +The ability to utilize a cluster of servers to provide redundancy and/or fail-over +is also available. + +.. caution:: + + **Requirements:** The `Memcached PHP extension`_ as well as a `Memcached server`_ + must be installed, active, and running to use this adapter. Version ``2.2`` or + greater of the `Memcached PHP extension`_ is required for this adapter. + +This adapter expects a `Memcached`_ instance to be passed as the first +parameter. A namespace and default cache lifetime can optionally be passed as +the second and third parameters:: + + use Symfony\Component\Cache\Adapter\MemcachedAdapter; + + $cache = new MemcachedAdapter( + // the client object that sets options and adds the server instance(s) + \Memcached $client, + + // a string prefixed to the keys of the items stored in this cache + $namespace = '', + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until MemcachedAdapter::clear() is invoked or the server(s) are restarted) + $defaultLifetime = 0 + ); + +Configure the Connection +------------------------ + +The :method:`Symfony\\Component\\Cache\\Adapter\\MemcachedAdapter::createConnection` +helper method allows creating and configuring a `Memcached`_ class instance using a +`Data Source Name (DSN)`_ or an array of DSNs:: + + use Symfony\Component\Cache\Adapter\MemcachedAdapter; + + // pass a single DSN string to register a single server with the client + $client = MemcachedAdapter::createConnection( + 'memcached://localhost' + ); + + // pass an array of DSN strings to register multiple servers with the client + $client = MemcachedAdapter::createConnection(array( + 'memcached://10.0.0.100', + 'memcached://10.0.0.101', + 'memcached://10.0.0.102', + // etc... + )); + +The `Data Source Name (DSN)`_ for this adapter must use the following format: + +.. code-block:: text + + memcached://[user:pass@][ip|host|socket[:port]][?weight=int] + +The DSN must include a IP/host (and an optional port) or a socket path, an +optional username and password (for SASL authentication; it requires that the +memcached extension was compiled with ``--enable-memcached-sasl``) and an +optional weight (for prioritizing servers in a cluster; its value is an integer +between ``0`` and ``100`` which defaults to ``null``; a higher value means more +priority). + +Below are common examples of valid DSNs showing a combination of available values:: + + use Symfony\Component\Cache\Adapter\MemcachedAdapter; + + $client = MemcachedAdapter::createConnection(array( + // hostname + port + 'memcached://my.server.com:11211' + + // hostname without port + SASL username and password + 'memcached://rmf:abcdef@localhost' + + // IP address instead of hostname + weight + 'memcached://127.0.0.1?weight=50' + + // socket instead of hostname/IP + SASL username and password + 'memcached://janesmith:mypassword@/var/run/memcached.sock' + + // socket instead of hostname/IP + weight + 'memcached:///var/run/memcached.sock?weight=20' + )); + +Configure the Options +--------------------- + +The :method:`Symfony\\Component\\Cache\\Adapter\\MemcachedAdapter::createConnection` +helper method also accepts an array of options as its second argument. The +expected format is an associative array of ``key => value`` pairs representing +option names and their respective values:: + + use Symfony\Component\Cache\Adapter\MemcachedAdapter; + + $client = MemcachedAdapter::createConnection( + // a DSN string or an array of DSN strings + array(), + + // associative array of configuration options + array( + 'compression' => true, + 'libketama_compatible' => true, + 'serializer' => 'igbinary', + ) + ); + +Available Options +~~~~~~~~~~~~~~~~~ + +``auto_eject_hosts`` (type: ``bool``, default: ``false``) + Enables or disables a constant, automatic, re-balancing of the cluster by + auto-ejecting hosts that have exceeded the configured ``server_failure_limit``. + +``buffer_writes`` (type: ``bool``, default: ``false``) + Enables or disables buffered input/output operations, causing storage + commands to buffer instead of being immediately sent to the remote + server(s). Any action that retrieves data, quits the connection, or closes + down the connection will cause the buffer to be committed. + +``compression`` (type: ``bool``, default: ``true``) + Enables or disables payload compression, where item values longer than 100 + bytes are compressed during storage and decompressed during retrieval. + +``compression_type`` (type: ``string``) + Specifies the compression method used on value payloads. when the + **compression** option is enabled. + + Valid option values include ``fastlz`` and ``zlib``, with a default value + that *varies based on flags used at compilation*. + +``connect_timeout`` (type: ``int``, default: ``1000``) + Specifies the timeout (in milliseconds) of socket connection operations when + the ``no_block`` option is enabled. + + Valid option values include *any positive integer*. + +``distribution`` (type: ``string``, default: ``consistent``) + Specifies the item key distribution method among the servers. Consistent + hashing delivers better distribution and allows servers to be added to the + cluster with minimal cache losses. + + Valid option values include ``modula``, ``consistent``, and ``virtual_bucket``. + +``hash`` (type: ``string``, default: ``md5``) + Specifies the hashing algorithm used for item keys. Each hash algorithm has + its advantages and its disadvantages. The default is suggested for compatibility + with other clients. + + Valid option values include ``default``, ``md5``, ``crc``, ``fnv1_64``, + ``fnv1a_64``, ``fnv1_32``, ``fnv1a_32``, ``hsieh``, and ``murmur``. + +``libketama_compatible`` (type: ``bool``, default: ``true``) + Enables or disables "libketama" compatible behavior, enabling other + libketama-based clients to access the keys stored by client instance + transparently (like Python and Ruby). Enabling this option sets the ``hash`` + option to ``md5`` and the ``distribution`` option to ``consistent``. + +``no_block`` (type: ``bool``, default: ``true``) + Enables or disables asynchronous input and output operations. This is the + fastest transport option available for storage functions. + +``number_of_replicas`` (type: ``int``, default: ``0``) + Specifies the number of replicas that should be stored for each item (on + different servers). This does not dedicate certain memcached servers to + store the replicas in, but instead stores the replicas together with all of + the other objects (on the "n" next servers registered). + + Valid option values include *any positive integer*. + +``prefix_key`` (type: ``string``, default: an empty string) + Specifies a "domain" (or "namespace") prepended to your keys. It cannot be + longer than 128 characters and reduces the maximum key size. + + Valid option values include *any alphanumeric string*. + +``poll_timeout`` (type: ``int``, default: ``1000``) + Specifies the amount of time (in seconds) before timing out during a socket + polling operation. + + Valid option values include *any positive integer*. + +``randomize_replica_read`` (type: ``bool``, type: ``false``) + Enables or disables randomization of the replica reads starting point. + Normally the read is done from primary server and in case of a miss the read + is done from "primary+1", then "primary+2", all the way to "n" replicas. + This option sets the replica reads as randomized between all available + servers; it allows distributing read load to multiple servers with the + expense of more write traffic. + +``recv_timeout`` (type: ``int``, default: ``0``) + Specifies the amount of time (in microseconds) before timing out during an outgoing socket (read) operation. + When the ``no_block`` option isn't enabled, this will allow you to still have timeouts on the reading of data. + + Valid option values include ``0`` or *any positive integer*. + +``retry_timeout`` (type: ``int``, default: ``0``) + Specifies the amount of time (in seconds) before timing out and retrying a + connection attempt. + + Valid option values include *any positive integer*. + +``send_timeout`` (type: ``int``, default: ``0``) + Specifies the amount of time (in microseconds) before timing out during an + incoming socket (send) operation. When the ``no_block`` option isn't enabled, + this will allow you to still have timeouts on the sending of data. + + Valid option values include ``0`` or *any positive integer*. + +``serializer`` (type: ``string``, default: ``php``) + Specifies the serializer to use for serializing non-scalar values. The + ``igbinary`` options requires the igbinary PHP extension to be enabled, as + well as the memcached extension to have been compiled with support for it. + + Valid option values include ``php`` and ``igbinary``. + +``server_failure_limit`` (type: ``int``, default: ``0``) + Specifies the failure limit for server connection attempts before marking + the server as "dead". The server will remaining in the server pool unless + ``auto_eject_hosts`` is enabled. + + Valid option values include *any positive integer*. + +``socket_recv_size`` (type: ``int``) + Specified the maximum buffer size (in bytes) in the context of incoming + (receive) socket connection data. + + Valid option values include *any positive integer*, with a default value + that *varies by platform and kernel configuration*. + +``socket_send_size`` (type: ``int``) + Specified the maximum buffer size (in bytes) in the context of outgoing (send) + socket connection data. + + Valid option values include *any positive integer*, with a default value + that *varies by platform and kernel configuration*. + +``tcp_keepalive`` (type: ``bool``, default: ``false``) + Enables or disables the "`keep-alive`_" `Transmission Control Protocol (TCP)`_ + feature, which is a feature that helps to determine whether the other end + has stopped responding by sending probes to the network peer after an idle + period and closing or persisting the socket based on the response (or lack thereof). + +``tcp_nodelay`` (type: ``bool``, default: ``false``) + Enables or disables the "`no-delay`_" (Nagle's algorithm) `Transmission Control Protocol (TCP)`_ + algorithm, which is a mechanism intended to improve the efficiency of + networks by reducing the overhead of TCP headers by combining a number of + small outgoing messages and sending them all at once. + +``use_udp`` (type: ``bool``, default: ``false``) + Enables or disabled the use of `User Datagram Protocol (UDP)`_ mode (instead + of `Transmission Control Protocol (TCP)`_ mode), where all operations are + executed in a "fire-and-forget" manner; no attempt to ensure the operation + has been received or acted on will be made once the client has executed it. + + .. caution:: + + Not all library operations are tested in this mode. Mixed TCP and UDP + servers are not allowed. + +``verify_key`` (type: ``bool``, default: ``false``) + Enables or disables testing and verifying of all keys used to ensure they + are valid and fit within the design of the protocol being used. + +.. tip:: + Reference the `Memcached`_ extension's `predefined constants`_ documentation + for additional information about the available options. + +.. _`Transmission Control Protocol (TCP)`: https://en.wikipedia.org/wiki/Transmission_Control_Protocol +.. _`User Datagram Protocol (UDP)`: https://en.wikipedia.org/wiki/User_Datagram_Protocol +.. _`no-delay`: https://en.wikipedia.org/wiki/TCP_NODELAY +.. _`keep-alive`: https://en.wikipedia.org/wiki/Keepalive +.. _`Memcached PHP extension`: http://php.net/manual/en/book.memcached.php +.. _`predefined constants`: http://php.net/manual/en/memcached.constants.php +.. _`Memcached server`: https://memcached.org/ +.. _`Memcached`: http://php.net/manual/en/class.memcached.php +.. _`Data Source Name (DSN)`: https://en.wikipedia.org/wiki/Data_source_name +.. _`Domain Name System (DNS)`: https://en.wikipedia.org/wiki/Domain_Name_System diff --git a/components/cache/adapters/pdo_doctrine_dbal_adapter.rst b/components/cache/adapters/pdo_doctrine_dbal_adapter.rst new file mode 100644 index 00000000000..76ac5860e89 --- /dev/null +++ b/components/cache/adapters/pdo_doctrine_dbal_adapter.rst @@ -0,0 +1,46 @@ +.. index:: + single: Cache Pool + single: PDO Cache, Doctrine DBAL Cache + +.. _`pdo-doctrine-adapter`: + +PDO & Doctrine DBAL Cache Adapter +================================= + +.. versionadded:: 3.2 + + The PDO & Doctrine DBAL adapter was introduced in Symfony 3.2. + + +This adapter stores the cache items in an SQL database. It requires a `PDO`_, +`Doctrine DBAL Connection`_, or `Data Source Name (DSN)`_ as its first parameter, and +optionally a namespace, default cache lifetime, and options array as its second, +third, and forth parameters:: + + use Symfony\Component\Cache\Adapter\PdoAdapter; + + $cache = new PdoAdapter( + + // a PDO, a Doctrine DBAL connection or DSN for lazy connecting through PDO + $databaseConnectionOrDSN, + + // the string prefixed to the keys of the items stored in this cache + $namespace = '', + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until the database table is truncated or its rows are otherwise deleted) + $defaultLifetime = 0, + + // an array of options for configuring the database connection + $options = array() + ); + +.. tip:: + + When passed a `Data Source Name (DSN)`_ string (instead of a database connection + class instance), the connection will be lazy-loaded when needed. + +.. _`PDO`: http://php.net/manual/en/class.pdo.php +.. _`Doctrine DBAL Connection`: https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Connection.php +.. _`Data Source Name (DSN)`: https://en.wikipedia.org/wiki/Data_source_name diff --git a/components/cache/adapters/php_array_cache_adapter.rst b/components/cache/adapters/php_array_cache_adapter.rst new file mode 100644 index 00000000000..2a45c3cf759 --- /dev/null +++ b/components/cache/adapters/php_array_cache_adapter.rst @@ -0,0 +1,38 @@ +.. index:: + single: Cache Pool + single: PHP Array Cache + +Php Array Cache Adapter +======================= + +This adapter is a highly performant way to cache static data (e.g. application configuration) +that is optimized and preloaded into OPcache memory storage:: + + use Symfony\Component\Cache\Adapter\PhpArrayAdapter; + use Symfony\Component\Cache\Adapter\PhpFilesAdapter; + + // somehow, decide it's time to warm up the cache! + if ($needsWarmup) { + // some static values + $values = array( + 'stats.num_products' => 4711, + 'stats.num_users' => 1356, + ); + + $cache = new PhpArrayAdapter( + // single file where values are cached + __DIR__ . '/somefile.cache', + // a backup adapter, if you set values after warmup + new FilesystemAdapter() + ); + $cache->warmUp($values); + } + + // ... then, use the cache! + $cacheItem = $cache->getItem('stats.num_users'); + echo $cacheItem->get(); + +.. note:: + + This adapter requires PHP 7.x and should be used with the php.ini setting + ``opcache.enable`` on. diff --git a/components/cache/adapters/proxy_adapter.rst b/components/cache/adapters/proxy_adapter.rst new file mode 100644 index 00000000000..86b24ead50f --- /dev/null +++ b/components/cache/adapters/proxy_adapter.rst @@ -0,0 +1,36 @@ +.. index:: + single: Cache Pool + single: Proxy Cache + +Proxy Cache Adapter +=================== + +This adapter wraps a `PSR-6`_ compliant `cache item pool interface`_. It is used to integrate +your application's cache item pool implementation with the Symfony :ref:`Cache Component ` +by consuming any implementation of ``Psr\Cache\CacheItemPoolInterface``. + +This adapter expects a ``Psr\Cache\CacheItemPoolInterface`` instance as its first parameter, +and optionally a namespace and default cache lifetime as its second and third parameters:: + + use Psr\Cache\CacheItemPoolInterface; + use Symfony\Component\Cache\Adapter\ProxyAdapter; + + $psr6CachePool = \\ create your own cache pool instance that implements the PSR-6 + \\ interface `CacheItemPoolInterface` + + $cache = new ProxyAdapter( + + // a cache pool instance + CacheItemPoolInterface $psr6CachePool, + + // a string prefixed to the keys of the items stored in this cache + $namespace = '', + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until the cache is cleared) + $defaultLifetime = 0 + ); + +.. _`PSR-6`: http://www.php-fig.org/psr/psr-6/ +.. _`cache item pool interface`: http://www.php-fig.org/psr/psr-6/#cacheitempoolinterface diff --git a/components/cache/adapters/redis_adapter.rst b/components/cache/adapters/redis_adapter.rst new file mode 100644 index 00000000000..bccd37657f0 --- /dev/null +++ b/components/cache/adapters/redis_adapter.rst @@ -0,0 +1,145 @@ +.. index:: + single: Cache Pool + single: Redis Cache + +.. _`redis-adapter`: + +Redis Cache Adapter +=================== + +This adapter stores the values in-memory using one (or more) `Redis server`_ instances. +Unlike the :ref:`APCu adapter `, and similarly to the +:ref:`Memcached adapter `, it is not limited to the current server's +shared memory; you can store contents independent of your PHP environment. The ability +to utilize a cluster of servers to provide redundancy and/or fail-over is also available. + +.. caution:: + + **Requirements:** At least one `Redis server`_ must be installed and running to use this + adapter. Additionally, this adapter requires a compatible extension or library that implements + ``\Redis``, ``\RedisArray``, ``RedisCluster``, or ``\Predis``. + +This adapter expects a `Redis`_, `RedisArray`_, `RedisCluster`_, or `Predis`_ instance to be +passed as the first parameter. A namespace and default cache lifetime can optionally be passed +as the second and third parameters:: + + use Symfony\Component\Cache\Adapter\RedisAdapter; + + $cache = new RedisAdapter( + + // the object that stores a valid connection to your Redis system + \Redis $redisConnection, + + // the string prefixed to the keys of the items stored in this cache + $namespace = '', + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until RedisAdapter::clear() is invoked or the server(s) are purged) + $defaultLifetime = 0 + ); + +Configure the Connection +------------------------ + +The :method:`Symfony\\Component\\Cache\\Adapter\\RedisAdapter::createConnection` +helper method allows creating and configuring the Redis client class instance using a +`Data Source Name (DSN)`_:: + + use Symfony\Component\Cache\Adapter\RedisAdapter; + + // pass a single DSN string to register a single server with the client + $client = RedisAdapter::createConnection( + 'redis://localhost' + ); + +The DSN can specify either an IP/host (and an optional port) or a socket path, as well as a user +and password and a database index. + +.. note:: + + A `Data Source Name (DSN)`_ for this adapter must use the following format. + + .. code-block:: text + + redis://[user:pass@][ip|host|socket[:port]][/db-index] + +Below are common examples of valid DSNs showing a combination of available values:: + + use Symfony\Component\Cache\Adapter\RedisAdapter; + + // host "my.server.com" and port "6379" + RedisAdapter::createConnection('redis://my.server.com:6379'); + + // host "my.server.com" and port "6379" and database index "20" + RedisAdapter::createConnection('redis://my.server.com:6379/20'); + + // host "localhost" and SASL use "rmf" and pass "abcdef" + RedisAdapter::createConnection('redis://rmf:abcdef@localhost'); + + // socket "/var/run/redis.sock" and SASL user "user1" and pass "bad-pass" + RedisAdapter::createConnection('redis://user1:bad-pass@/var/run/redis.sock'); + +Configure the Options +--------------------- + +The :method:`Symfony\\Component\\Cache\\Adapter\\RedisAdapter::createConnection` helper method +also accepts an array of options as its second argument. The expected format is an associative +array of ``key => value`` pairs representing option names and their respective values:: + + use Symfony\Component\Cache\Adapter\RedisAdapter; + + $client = RedisAdapter::createConnection( + + // provide a string dsn + 'redis://localhost:6739', + + // associative array of configuration options + array( + 'persistent' => 0, + 'persistent_id' => null, + 'timeout' => 30, + 'read_timeout' => 0, + 'retry_interval' => 0, + ) + + ); + +Available Options +~~~~~~~~~~~~~~~~~ + +``class`` (type: ``string``) + Specifies the connection library to return, either ``\Redis`` or ``\Predis\Client``. + If none is specified, it will return ``\Redis`` if the ``redis`` extension is + available, and ``\Predis\Client`` otherwise. + +``persistent`` (type: ``int``, default: ``0``) + Enables or disables use of persistent connections. A value of ``0`` disables persistent + connections, and a value of ``1`` enables them. + +``persistent_id`` (type: ``string|null``, default: ``null``) + Specifies the persistent id string to use for a persistent connection. + +``read_timeout`` (type: ``int``, default: ``0``) + Specifies the time (in seconds) used when performing read operations on the underlying + network resource before the operation times out. + +``retry_interval`` (type: ``int``, default: ``0``) + Specifies the delay (in milliseconds) between reconnection attempts in case the client + loses connection with the server. + +``timeout`` (type: ``int``, default: ``30``) + Specifies the time (in seconds) used to connect to a Redis server before the + connection attempt times out. + +.. note:: + When using the `Predis`_ library some additional Predis-specific options are available. + Reference the `Predis Connection Parameters`_ documentation for more information. + +.. _`Data Source Name (DSN)`: https://en.wikipedia.org/wiki/Data_source_name +.. _`Redis server`: https://redis.io/ +.. _`Redis`: https://github.com/phpredis/phpredis +.. _`RedisArray`: https://github.com/phpredis/phpredis/blob/master/arrays.markdown#readme +.. _`RedisCluster`: https://github.com/phpredis/phpredis/blob/master/cluster.markdown#readme +.. _`Predis`: https://packagist.org/packages/predis/predis +.. _`Predis Connection Parameters`: https://github.com/nrk/predis/wiki/Connection-Parameters#list-of-connection-parameters diff --git a/components/cache/cache_invalidation.rst b/components/cache/cache_invalidation.rst index 443700e1bf1..fe661c618ab 100644 --- a/components/cache/cache_invalidation.rst +++ b/components/cache/cache_invalidation.rst @@ -1,6 +1,6 @@ .. index:: - single: Cache; Invalidation - single: Cache; Tags + single: Cache; Invalidation + single: Cache; Tags Cache Invalidation ================== diff --git a/components/cache/cache_items.rst b/components/cache/cache_items.rst index 71c1e9b39da..b534721859e 100644 --- a/components/cache/cache_items.rst +++ b/components/cache/cache_items.rst @@ -1,7 +1,7 @@ .. index:: - single: Cache Item - single: Cache Expiration - single: Cache Exceptions + single: Cache Item + single: Cache Expiration + single: Cache Exceptions Cache Items =========== diff --git a/components/cache/cache_pools.rst b/components/cache/cache_pools.rst index 948a5de5e5d..bb6acad746f 100644 --- a/components/cache/cache_pools.rst +++ b/components/cache/cache_pools.rst @@ -1,9 +1,13 @@ .. index:: - single: Cache Pool - single: APC Cache, APCu Cache - single: Doctrine Cache - single: Redis Cache - single: PDO Cache, Doctrine DBAL Cache + single: Cache Pool + single: APC Cache, APCu Cache + single: Array Cache + single: Chain Cache + single: Doctrine Cache + single: Filesystem Cache + single: Memcached Cache + single: PDO Cache, Doctrine DBAL Cache + single: Redis Cache Cache Pools and Supported Adapters ================================== @@ -21,289 +25,11 @@ Cache Pools are created through the **cache adapters**, which are classes that implement :class:`Symfony\\Component\\Cache\\Adapter\\AdapterInterface`. This component provides several adapters ready to use in your applications. -Array Cache Adapter -~~~~~~~~~~~~~~~~~~~ +.. toctree:: + :glob: + :maxdepth: 1 -This adapter is only useful for testing purposes because contents are stored in -memory and not persisted in any way. Besides, some features explained later are -not available, such as the deferred saves:: - - use Symfony\Component\Cache\Adapter\ArrayAdapter; - - $cache = new ArrayAdapter( - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the current PHP process finishes) - $defaultLifetime = 0, - // if ``true``, the values saved in the cache are serialized before storing them - $storeSerialized = true - ); - -Filesystem Cache Adapter -~~~~~~~~~~~~~~~~~~~~~~~~ - -This adapter is useful when you want to improve the application performance but -can't install tools like APCu or Redis in the server. This adapter stores the -contents as regular files in a set of directories on the local file system:: - - use Symfony\Component\Cache\Adapter\FilesystemAdapter; - - $cache = new FilesystemAdapter( - // the subdirectory of the main cache directory where cache items are stored - $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the files are deleted) - $defaultLifetime = 0, - // the main cache directory (the application needs read-write permissions on it) - // if none is specified, a directory is created inside the system temporary directory - $directory = null - ); - -Php Files Cache Adapter -~~~~~~~~~~~~~~~~~~~~~~~ - -This adapter is very similar to the Filesystem adapter, except that the saving creates -a ``.php`` file, which is included on fetch (allowing the file to be saved in OPcache):: - - use Symfony\Component\Cache\Adapter\PhpFilesAdapter; - - $cache = new PhpFilesAdapter( - // the subdirectory of the main cache directory where cache items are stored - $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the files are deleted) - $defaultLifetime = 0, - // the main cache directory (the application needs read-write permissions on it) - // if none is specified, a directory is created inside the system temporary directory - $directory = null - ); - -APCu Cache Adapter -~~~~~~~~~~~~~~~~~~ - -This adapter can increase the application performance very significantly, -because contents are cached in the shared memory of your server, which is much -faster than the file system. It requires to have installed and enabled the PHP -APCu extension. It's not recommended to use it when performing lots of write and -delete operations because it produces fragmentation in the APCu memory that can -degrade performance significantly:: - - use Symfony\Component\Cache\Adapter\ApcuAdapter; - - $cache = new ApcuAdapter( - // the string prefixed to the keys of the items stored in this cache - $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the APC memory is deleted) - $defaultLifetime = 0, - // if present, this string is added to the namespace to simplify the - // invalidation of the entire cache (e.g. when deploying the application) - $version = null - ); - -Redis Cache Adapter -~~~~~~~~~~~~~~~~~~~ - -This adapter stores the contents in the memory of a Redis server. Unlike the APCu -adapter, it's not limited to the shared memory of the current server, so you can -store contents in a cluster of servers if needed. - -Before you start, make sure you have Redis running and have created a connection -that implements the ``\Redis``, ``\RedisArray``, ``\RedisCluster`` or ``\Predis`` -classes:: - - use Symfony\Component\Cache\Adapter\RedisAdapter; - - $cache = new RedisAdapter( - // the object that stores a valid connection to your Redis system - \Redis $redisConnection, - // the string prefixed to the keys of the items stored in this cache - $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the Redis memory is deleted) - $defaultLifetime = 0 - ); - -The :method:`Symfony\\Component\\Cache\\Adapter\\RedisAdapter::createConnection` -helper allows creating a connection to a Redis server using a DSN configuration:: - - $redisConnection = RedisAdapter::createConnection('redis://localhost'); - - $cache = new RedisAdapter($redisConnection); - -See the method's docblock for more options. - -Memcached Cache Adapter -~~~~~~~~~~~~~~~~~~~~~~~ - -This adapter stores the contents into a set of `Memcached`_ servers. - -Before you start, make sure you have Memcached running and have created a -:phpclass:`Memcached` object:: - - use Symfony\Component\Cache\Adapter\MemcachedAdapter; - - $cache = new MemcachedAdapter( - // the object that stores a valid connection to your Memcached servers - \Memcached $client, - // the string prefixed to the keys of the items stored in this cache - $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the Memcached memory is deleted) - $defaultLifetime = 0 - ); - -The :method:`Symfony\\Component\\Cache\\Adapter\\Memcached::createConnection` -helper allows creating a connection to a pool of Memcached server using a DSN configuration:: - - $memcachedClient = MemcachedAdapter::createConnection( - 'memcached://user:pass@localhost?weight=33', - - // options, including username, password and Memcached::OPT_* options - array('persistent_id' => '_products_cache') - ); - - // alternate syntax: array notations for the servers - $memcachedClient = MemcachedAdapter::createConnection(array( - array('192.168.1.100', 11211, 33), - array('192.168.1.101', 11211, 33) - )); - - $cache = new MemcachedAdapter($memcachedClient); - -See the method's docblock for more options. - -PDO & Doctrine DBAL Cache Adapter -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: 3.2 - The PDO & Doctrine DBAL adapter was introduced in Symfony 3.2. - -This adapter stores the cached items a SQL database accessed through a PDO or a -Doctrine DBAL connection:: - - use Symfony\Component\Cache\Adapter\PdoAdapter; - - $cache = new PdoAdapter( - // a PDO, a Doctrine DBAL connection or DSN for lazy connecting through PDO - $databaseConnectionOrDSN, - // the string prefixed to the keys of the items stored in this cache - $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the database is cleared) - $defaultLifetime = 0, - // an array of options for configuring the database connection - $options = array() - ); - -Chain Cache Adapter -~~~~~~~~~~~~~~~~~~~ - -This adapter allows to combine any number of the previous adapters. Cache items -are fetched from the first adapter which contains them. Besides, cache items are -saved in all the given adapters, so this is a simple way of creating a cache -replication:: - - use Symfony\Component\Cache\Adapter\ApcuAdapter; - use Symfony\Component\Cache\Adapter\ChainAdapter; - use Symfony\Component\Cache\Adapter\FilesystemAdapter; - - $apcCache = new ApcuAdapter(); - $fileCache = new FilesystemAdapter(); - - $cache = new ChainAdapter(array($apcCache, $fileCache)); - -When an item is not found in the first adapters but is found in the next ones, -the ``ChainAdapter`` ensures that the fetched item is saved in all the adapters -where it was missing. Since it's not possible to know the expiry date and time -of a cache item, the second optional argument of ``ChainAdapter`` is the default -lifetime applied to those cache items (by default it's ``0``). - -Traceable Adapter -~~~~~~~~~~~~~~~~~ - -This adapter wraps another adapter, and allows you to read a report of all of the -"calls" made to the adapter, including how long actions took, cache hits, misses -and more:: - - use Symfony\Component\Cache\Adapter\TraceableAdapter; - use Symfony\Component\Cache\Adapter\FilesystemAdapter; - - $fileCache = new FilesystemAdapter(); - - $cache = new TraceableAdapter($fileCache); - - // work with the $cache adapter like normal - - // returns an array of TraceableAdapterEvent describing the calls - $events = $cache->getCalls(); - -Proxy Cache Adapter -~~~~~~~~~~~~~~~~~~~ - -This adapter is useful to integrate in your application cache pools not created -with the Symfony Cache component. As long as those cache pools implement the -``CacheItemPoolInterface`` interface, this adapter allows you to get items from -that external cache and save them in the Symfony cache of your application:: - - use Symfony\Component\Cache\Adapter\ProxyAdapter; - - // ... create $nonSymfonyCache somehow - $cache = new ProxyAdapter($nonSymfonyCache); - -The adapter accepts two additional optional arguments: the namespace (``''`` by -default) and the default lifetime (``0`` by default). - -Doctrine Cache Adapter -~~~~~~~~~~~~~~~~~~~~~~ - -This adapter wraps any `Doctrine Cache`_ provider so you can use them in your -application as if they were Symfony Cache adapters:: - - use Doctrine\Common\Cache\SQLite3Cache; - use Symfony\Component\Cache\Adapter\DoctrineAdapter; - - $sqliteDatabase = new \SQLite3(__DIR__.'/cache/data.sqlite'); - $doctrineCache = new SQLite3Cache($sqliteDatabase, 'tableName'); - $symfonyCache = new DoctrineAdapter($doctrineCache); - -This adapter also defines two optional arguments called ``namespace`` (default: -``''``) and ``defaultLifetime`` (default: ``0``) and adapts them to make them -work in the underlying Doctrine cache. - -Php Array Cache Adapter -~~~~~~~~~~~~~~~~~~~~~~~ - -This adapter is a highly performant way to cache static data (e.g. application configuration) -that is optimized and preloaded into OPcache memory storage:: - - use Symfony\Component\Cache\Adapter\PhpArrayAdapter; - use Symfony\Component\Cache\Adapter\PhpFilesAdapter; - - // somehow, decide it's time to warm up the cache! - if ($needsWarmup) { - // some static values - $values = array( - 'stats.num_products' => 4711, - 'stats.num_users' => 1356, - ); - - $cache = new PhpArrayAdapter( - // single file where values are cached - __DIR__ . '/somefile.cache', - // a backup adapter, if you set values after warmup - new FilesystemAdapter() - ); - $cache->warmUp($values); - } - - // ... then, use the cache! - $cacheItem = $cache->getItem('stats.num_users'); - echo $cacheItem->get(); - -.. note:: - - This adapter requires PHP 7.x and should be used with the php.ini setting - ``opcache.enable`` on. + adapters/* Looking for Cache Items ----------------------- @@ -393,6 +119,3 @@ when all items are successfully deleted):: // ... $cacheIsEmpty = $cache->clear(); - -.. _`Doctrine Cache`: https://github.com/doctrine/cache -.. _`Memcached`: http://php.net/manual/en/book.memcached.php