Search by

blazon / psr11-symfony-cache

wshafer

Symfony Cache Component Factories for PSR-11

Package info

gitlab.com/blazon/psr11-symfony-cache

Issues

pkg:composer/blazon/psr11-symfony-cache

Statistics

Installs: 1 251

Dependents: 0

Suggesters: 0

Stars: 0

0.0.2 2021-07-19 20:25 UTC

This package is auto-updated.

Last update: 2026-10-05 04:33:51 UTC


README

codecov pipeline status

PSR-11 Symfony Cache

Symfony Cache Component Factories for PSR-11.

Table of Contents

Installation

composer require blazon/psr11-symfony-cache

Requires PHP 8.4+ and symfony/cache 8.1+.

Usage

<?php
/** @var \Symfony\Component\Cache\Adapter\AdapterInterface $cache */
$cache = $container->get('other');

// The callable will only be executed on a cache miss.
$value = $cache->get('my_cache_key', function (\Symfony\Contracts\Cache\ItemInterface $item) {
    $item->expiresAfter(3600);

    // ... do some HTTP request or heavy computations
    $computedValue = 'foobar';

    return $computedValue;
});

echo $value; // 'foobar'

Additional info can be found in the documentation

PSR-16 Simple Cache

Blazon\PSR11SymfonyCache\Psr16CacheFactory builds a PSR-16 Psr\SimpleCache\CacheInterface from the same configuration, using Symfony's Psr16Cache. Register it the same way as CacheFactory. It requires psr/simple-cache.

<?php
// Pimple: uses the "default" cache configuration
$container['simple-cache'] = new \Blazon\PSR11SymfonyCache\Psr16CacheFactory();

// Pimple: uses the "other" cache configuration
$container['other-simple-cache'] = function ($c) {
    return \Blazon\PSR11SymfonyCache\Psr16CacheFactory::other($c);
};

// Laminas Service Manager factories
'factories' => [
    'simple-cache' => \Blazon\PSR11SymfonyCache\Psr16CacheFactory::class,
    'other-simple-cache' => [\Blazon\PSR11SymfonyCache\Psr16CacheFactory::class, 'other'],
],

Containers

Any PSR-11 container wil work. In order to do that you will need to add configuration and register a new service that points to Blazon\PSR11SymfonyCache\CacheFactory

Below are some specific container examples to get you started

Pimple Example

// Create Container
$container = new \Xtreamwayz\Pimple\Container([
    // Cache using the default keys.
    'cache' => new \Blazon\PSR11SymfonyCache\CacheFactory(),
    
    // Second cache using a different cache configuration
    'other' => function($c) {
        return \Blazon\PSR11SymfonyCache\CacheFactory::other($c);
    },
    
    // Config
    'config' => [
        'cache' => [
            // At the bare minimum you must include a default adaptor.
            'default' => [
                'type' => 'filesystem',
                'options' => [
                    'directory' => '/tmp/cache',
                ],
            ],
            
            // Some other adaptor.  Keys are the names for each adaptor
            'other' => [
                'type' => 'array',
                'options' => [],
            ],
        ],
    ]
]);

/** @var \Symfony\Component\Cache\Adapter\AdapterInterface $cache */
$cache = $container->get('other');
// The callable will only be executed on a cache miss.
$value = $cache->get('my_cache_key', function (\Symfony\Contracts\Cache\ItemInterface $item) {
    $item->expiresAfter(3600);

    // ... do some HTTP request or heavy computations
    $computedValue = 'foobar';

    return $computedValue;
});

echo $value; // 'foobar'

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

Laminas Service Manager

// Create the container and define the services you'd like to use
$container = new \Laminas\ServiceManager\ServiceManager([
    'factories' => [
        // Cache using the default keys.
        'cache' => \Blazon\PSR11SymfonyCache\CacheFactory::class,
        
        // Second cache using a different cache configuration
        'other' => [\Blazon\PSR11SymfonyCache\CacheFactory::class, 'other'],
    ],
]);

// Config
$container->setService('config', [
    'cache' => [
        // At the bare minimum you must include a default adaptor.
        'default' => [
            'type' => 'filesystem',
            'options' => [
                'directory' => '/tmp/cache',
            ],
        ],
        
        // Some other adaptor.  Keys are the names for each adaptor
        'other' => [
            'type' => 'array',
            'options' => [],
        ],
    ],
]);

/** @var \Symfony\Component\Cache\Adapter\AdapterInterface $cache */
$cache = $container->get('other');
// The callable will only be executed on a cache miss.
$value = $cache->get('my_cache_key', function (\Symfony\Contracts\Cache\ItemInterface $item) {
    $item->expiresAfter(3600);

    // ... do some HTTP request or heavy computations
    $computedValue = 'foobar';

    return $computedValue;
});

echo $value; // 'foobar'

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

Frameworks

Any framework that use a PSR-11 should work fine. Below are some specific framework examples to get you started

Mezzio

You'll need to add configuration and register the services you'd like to use. There are number of ways to do that but the recommended way is to create a new config file config/autoload/cache.global.php

Configuration

config/autoload/cache.global.php

<?php
return [
    'dependencies' => [
        'factories' => [
            // Cache using the default keys.
            'cache' => \Blazon\PSR11SymfonyCache\CacheFactory::class,
            
            // Second cache using a different cache configuration
            'other' => [\Blazon\PSR11SymfonyCache\CacheFactory::class, 'other'],
        ],
    ],
    
    'cache' => [
        // At the bare minimum you must include a default adaptor.
        'default' => [
            'type' => 'filesystem',
            'options' => [
                'directory' => '/tmp/cache',
            ],
        ],
        
        // Some other adaptor.  Keys are the names for each adaptor
        'other' => [
            'type' => 'array',
            'options' => [],
        ],
    ],
];

Laminas

You'll need to add configuration and register the services you'd like to use. There are number of ways to do that but the recommended way is to create a new config file config/autoload/cache.global.php

Configuration

config/autoload/cache.global.php

<?php
return [
    'service_manager' => [
        'factories' => [
            // Cache using the default keys.
            'cache' => \Blazon\PSR11SymfonyCache\CacheFactory::class,
            
            // Second cache using a different configuration
            'other' => [\Blazon\PSR11SymfonyCache\CacheFactory::class, 'other'],
        ],
    ],
    
    'cache' => [
        // At the bare minimum you must include a default adaptor.
        'default' => [
            'type' => 'filesystem',
            'options' => [
                'directory' => '/tmp/cache',
            ],
        ],
        
        // Some other adaptor.  Keys are the names for each adaptor
        'other' => [
            'type' => 'array',
            'options' => [],
        ],
    ],
];

Slim

public/index.php

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Symfony\Component\Cache\Adapter\AdapterInterface;
use \Symfony\Contracts\Cache\ItemInterface;

require '../vendor/autoload.php';

// Add Configuration
$config = [
    'settings' => [
        'cache' => [
            // At the bare minimum you must include a default adaptor.
            'default' => [
                'type' => 'filesystem',
                'options' => [
                    'directory' => '/tmp/cache',
                ],
            ],
            
            // Some other adaptor.  Keys are the names for each adaptor
            'other' => [
                'type' => 'array',
                'options' => [],
            ],
        ],
    ],
];

$app = new \Slim\App($config);

// Wire up the factory
$container = $app->getContainer();

// Cache using the default keys.
$container['cache'] = new \Blazon\PSR11SymfonyCache\CacheFactory();

// Second cache using a different cache configuration
$container['other'] = function ($c) {
    return \Blazon\PSR11SymfonyCache\CacheFactory::other($c);
};


// Example usage
$app->get('/example', function (Request $request, Response $response) {
    
    /** @var AdapterInterface $cache */
    $cache = $this->get('other');
    // The callable will only be executed on a cache miss.
    $value = $cache->get('my_cache_key', function (ItemInterface $item) {
        $item->expiresAfter(3600);
    
        // ... do some HTTP request or heavy computations
        $computedValue = 'foobar';
    
        return $computedValue;
    });
    
    echo $value; // 'foobar'
    
    // ... and to remove the cache key
    $cache->delete('my_cache_key');
});

$app->run();

Configuration

Minimal Configuration

A minimal configuration would consist of at least defining one service and the "default" adaptor.

Minimal Example (using Mezzio for the example)

<?php

return [
    'cache' => [
        'default' => [
            'type' => 'filesystem',
            'options' => [
                'directory' => '/tmp/cache',
            ],
        ],
    ],
];

Using this setup, the "default" cache service stores items on the local filesystem in /tmp/cache.

Full Configuration

Note: A "default" adaptor is required.

Full Example

<?php

return [
    'cache' => [
        // At the bare minimum you must include a default adaptor.
        'default' => [
            'type' => 'filesystem',
            'options' => [
                'directory' => '/tmp/cache',

                // Optional : how values are serialized.  A type name, such as 'deflate', or a type with options.
                // See Marshallers.
                'marshaller' => [
                    'type' => 'deflate',
                    'options' => [
                        'marshaller' => 'default', // The marshaller to compress the output of
                    ],
                ],
            ],
        ],
        
        // Some other adaptor.  Keys are the names for each adaptor
        'other' => [
            'type' => 'array',
            'options' => [],
        ],
    ],
];

Adaptors

Example configs for supported adaptors

APCu

This adapter is a high-performance, shared memory cache. It can significantly increase an application’s performance, as its cache contents are stored in shared memory, a component appreciably faster than many others, such as the filesystem.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'APCu',
            'options' => [
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: 0
                'version' => null, // Optional : Version of the cache items.
                'marshaller' => null, // Optional : a marshaller type name, or ['type' => ..., 'options' => [...]].  See Marshallers.  Default: Symfony's DefaultMarshaller
                'logger' => null, // Optional : a PSR-3 logger service name from the container.  See Logging.  Default: no logging
            ],
        ],
    ],
];

Docs: APCu Cache Adapter

Array

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 getValues() method

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'Array',
            'options' => [
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: 0
                'deepClone' => true, // Optional : store copies of values, so later changes to an object do not change the cached value.  Default: true
                'maxLifetime' => 0, // Optional : the maximum lifetime (in seconds) of the entire cache.  Default: 0
                'maxItems' => 0, // Optional : the maximum number of items that can be stored in the cache.  Default: 0
                'clock' => 'service-name', // Optional : a Psr\Clock\ClockInterface service, used instead of the system time.  Requires psr/clock
                'logger' => null, // Optional : a PSR-3 logger service name from the container.  See Logging.  Default: no logging
            ],
        ],
    ],
];

Docs: Array Cache Adapter

Chain

This adapter allows combining any number of the other available cache adapters. Cache items are fetched from the first adapter containing them and cache items are saved to all the given adapters. This exposes a simple and efficient method for creating a layered cache.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'Chain',
            'options' => [
                'adapters' => [], // Required : The ordered list of adapter service names to fetch cached items
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: 0
            ],
        ],
    ],
];

Docs: Chain Cache Adapter

Doctrine DBAL

This adapter stores the cache items in an SQL database through a Doctrine DBAL connection. It requires doctrine/dbal 4.3 or later.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'DoctrineDbal',
            'options' => [
                'client' => 'service-name', // Required: A \Doctrine\DBAL\Connection service name, or a dsn like 'mysql://user:pass@host/db'

                'db_table' => 'cache_items', // Optional.  The name of the table.  Default: cache_items
                'db_id_col' => 'item_id', // Optional.  The column where to store the cache id.  Default: item_id
                'db_data_col' => 'item_data', // Optional.  The column where to store the cache data.  Default: item_data
                'db_lifetime_col' => 'item_lifetime', // Optional.  The column where to store the lifetime.  Default: item_lifetime
                'db_time_col' => 'item_time', // Optional.  The column where to store the timestamp.  Default: item_time

                // Cache Config
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: 0
                'marshaller' => null, // Optional : a marshaller type name, or ['type' => ..., 'options' => [...]].  See Marshallers.  Default: Symfony's DefaultMarshaller
                'logger' => null, // Optional : a PSR-3 logger service name from the container.  See Logging.  Default: no logging
            ],
        ],
    ],
];

Docs: PDO & Doctrine DBAL Cache Adapter

Filesystem

This adapter offers improved application performance for those who cannot install tools like APCu or Redis in their environment. It stores the cache item expiration and content as regular files in a collection of directories on a locally mounted filesystem.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'Filesystem',
            'options' => [
                'directory' => '', // Optional : The main cache directory.  Default: directory is created inside the system temporary directory
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: '0'
                'marshaller' => null, // Optional : a marshaller type name, or ['type' => ..., 'options' => [...]].  See Marshallers.  Default: Symfony's DefaultMarshaller
                'logger' => null, // Optional : a PSR-3 logger service name from the container.  See Logging.  Default: no logging
            ],
        ],
    ],
];

Docs: Filesystem Cache Adapter

Filesystem Tag Aware

The same as the Filesystem adapter, with built-in support for tag-based invalidation.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'FilesystemTagAware',
            'options' => [
                'directory' => '', // Optional : The main cache directory.  Default: directory is created inside the system temporary directory
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: '0'
                'marshaller' => null, // Optional : a marshaller type name, or ['type' => ..., 'options' => [...]].  See Marshallers.  Default: Symfony's DefaultMarshaller
                'logger' => null, // Optional : a PSR-3 logger service name from the container.  See Logging.  Default: no logging
            ],
        ],
    ],
];

Docs: Cache Invalidation

Memcached

This adapter stores the values in-memory using one (or more) Memcached server instances. Unlike the APCu adapter, and similarly to the 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.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'Memcached',
            'options' => [
                // Connection config
                // A client service, or dsn(s).  Default: localhost
                'client' => 'service-name', // Memcached service name.  Will be pulled from the container.
                'dsn' => 'memcached://[user:pass@][ip|host|socket[:port]][?weight=int]', // One dsn or an array of dsn's.  Query parameters are options too

                // Connection Options.  Not needed if using a service.
                // Only these options are passed to Symfony's MemcachedAdapter::createConnection().  Leave an option out
                // to use the default.  Options can also be set in the DSN query string.
                'persistent_id' => null, // Optional.  Enables persistent connections, shared by clients with the same id.  Default: null
                'username' => null, // Optional.  SASL username.  Requires the binary protocol, which Symfony enables.  Default: null
                'password' => null, // Optional.  SASL password.  Default: null
                'auto_eject_hosts' => false, // Optional.  Remove servers that fail server_failure_limit times.  Default: false
                'buffer_writes' => false, // Optional.  Buffer writes until a read, or the buffer is full.  Default: false
                'compression' => true, // Optional.  Compress large values.  Default: true
                'compression_type' => null, // Optional.  \Memcached::COMPRESSION_FASTLZ or \Memcached::COMPRESSION_ZLIB (a constant, not a name).  Default: fastlz
                'connect_timeout' => 4000, // Optional.  The connect timeout (in milliseconds), in non-blocking mode.  Default: 4000
                'distribution' => 'consistent', // Optional.  modula, consistent or virtual_bucket.  Requires libketama_compatible => false.  Default: libketama's
                'hash' => 'md5', // Optional.  default, md5, crc, fnv1_64, fnv1a_64, fnv1_32, fnv1a_32, hsieh or murmur.  Requires libketama_compatible => false.  Default: md5
                'libketama_compatible' => true, // Optional.  Libketama compatible consistent hashing, which sets its own distribution and hash.  Default: true
                'no_block' => true, // Optional.  Asynchronous I/O.  Default: true
                'number_of_replicas' => 0, // Optional.  The number of replicas stored for each item.  Default: 0
                'prefix_key' => '', // Optional.  A prefix added to every key, at the Memcached level.  Default: ''
                'poll_timeout' => 5000, // Optional.  The poll timeout (in milliseconds).  Default: 5000
                'randomize_replica_read' => false, // Optional.  Read from a random replica.  Default: false
                'recv_timeout' => 0, // Optional.  The receive timeout (in microseconds).  Default: 0
                'retry_timeout' => 2, // Optional.  The time (in seconds) before retrying a failed server.  Default: 2
                'send_timeout' => 0, // Optional.  The send timeout (in microseconds).  Default: 0
                'serializer' => 'php', // Optional.  php, igbinary, json or msgpack.  Default: php
                'server_failure_limit' => 5, // Optional.  The number of failed attempts before a server is ejected.  Must be at least 1.  Default: 5
                'socket_recv_size' => null, // Optional.  The socket receive buffer size (in bytes).  Default: the system default
                'socket_send_size' => null, // Optional.  The socket send buffer size (in bytes).  Default: the system default
                'tcp_keepalive' => false, // Optional.  Enables TCP keepalive.  Default: false
                'tcp_nodelay' => true, // Optional.  Disables Nagle's algorithm.  Default: true
                'use_udp' => false, // Optional.  Use UDP instead of TCP.  Default: false
                'verify_key' => false, // Optional.  Check keys are valid before sending them.  Default: false
                // hash, serializer and distribution take a name, as above.
                
                // Cache Config
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: 0
                'marshaller' => null, // Optional : a marshaller type name, or ['type' => ..., 'options' => [...]].  See Marshallers.  Default: Symfony's DefaultMarshaller
                'logger' => null, // Optional : a PSR-3 logger service name from the container.  See Logging.  Default: no logging
            ],
        ],
    ],
];

Docs: Memcached Cache Adapter

Null

This adapter stores nothing: every read is a miss. Use it to turn caching off, for example in development or tests.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'Null',
        ],
    ],
];

PDO

This adapter stores the cache items in an SQL database.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'PDO',
            'options' => [
                'client' => 'service-name', // Required: A client service, or dsn(s). 
                
                'db_table' => 'cache_items', // Optional.  The name of the table.  Default: cache_items
                'db_id_col' => 'item_id', // Optional.  The column where to store the cache id.  Default: item_id
                'db_data_col' => 'item_data', // Optional.  The column where to store the cache data.  Default: item_data
                'db_lifetime_col' => 'item_lifetime', // Optional.  The column where to store the lifetime.  Default: item_lifetime
                'db_time_col' => 'item_time', // Optional.  The column where to store the timestamp.  Default: item_time
                'db_username' => '', // Optional.  The username when lazy-connect
                'db_password' => '', // Optional.  The password when lazy-connect
                'db_connection_options' => '', // Optional.  An array of driver-specific connection options
                
                // Cache Config
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: 0
                'marshaller' => null, // Optional : a marshaller type name, or ['type' => ..., 'options' => [...]].  See Marshallers.  Default: Symfony's DefaultMarshaller
                'logger' => null, // Optional : a PSR-3 logger service name from the container.  See Logging.  Default: no logging
            ],
        ],
    ],
];

Docs: PDO Cache Adapter

PHP Array

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

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'PhpArray',
            'options' => [
                'filePath' => __DIR__ . '/somefile.cache', // Required: Single file where values are cached
                'backupCache' => 'service-name', // Required: A backup cache service
            ],
        ],
    ],
];

Docs: PHP Array Cache Adapter

PHP Files

Similarly to Filesystem Adapter, this cache implementation writes cache entries out to disk, but unlike the Filesystem cache adapter, the PHP Files cache adapter writes and reads back these cache files as native PHP code.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'PhpFiles',
            'options' => [
                'directory' => '/some/dir/path', // Required: The main cache directory (the application needs read-write permissions on it)
                'appendOnly' => false, // Optional : skip the checks needed when files can be overwritten, for caches that only ever add new keys.  Default: false
                
                // Cache Config
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: 0
                'logger' => null, // Optional : a PSR-3 logger service name from the container.  See Logging.  Default: no logging
            ],
        ],
    ],
];

Docs: PHP Files Cache Adapter

Proxy

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 Cache Component by consuming any implementation of Psr\Cache\CacheItemPoolInterface.

It can also be used to prefix all keys automatically before storing items in the decorated pool, effectively allowing the creation of several namespaced pools out of a single one.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'proxy',
            'options' => [
                'psr6Service' => 'service-name', // Required: A PSR 6 cache service

                // Cache Config
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: 0
            ],
        ],
    ],
];

Docs: Proxy Cache Adapter

PSR-16

This adapter wraps a PSR-16 simple cache, so any implementation of Psr\SimpleCache\CacheInterface can be used as a Symfony Cache pool. It requires psr/simple-cache.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'Psr16',
            'options' => [
                'psr16Service' => 'service-name', // Required: A PSR 16 cache service

                // Cache Config
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: 0
                'logger' => null, // Optional : a PSR-3 logger service name from the container.  See Logging.  Default: no logging
            ],
        ],
    ],
];

Docs: PSR-16 Cache Adapter

Redis

This adapter stores the values in-memory using one (or more) Redis server instances.

Unlike the APCu adapter, and similarly to the 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.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'Redis',
            'options' => [
                // Connection config
                // A client service, or dsn(s) is required.  Default: localhost
                'client' => 'service-name', // Redis service name.  Will be pulled from the container.
                'dsn' => 'redis://[pass@][ip|host|socket[:port]][/db-index]', // Dsn for connections.

                // Connection Options.  Not needed if using a service.
                // Only these options are passed to Symfony's RedisAdapter::createConnection().  Leave an option out to
                // use Symfony's default.  Options can also be set in the DSN query string, which takes precedence.
                'class' => null, // Optional.  \Redis, \Relay\Relay or \Predis\Client.  Default: the first one available, in that order
                'auth' => null, // Optional.  A password, or [username, password] for ACL.  With sentinel, these are the sentinel credentials
                'persistent' => 0, // Optional.  Enables (1) or disables (0) persistent connections.  Default: 0
                'persistent_id' => null, // Optional.  The persistent id string to use for a persistent connection.  Default: null
                'timeout' => 30, // Optional.  The timeout (in seconds) used to connect to a Redis server.  Default: 30
                'read_timeout' => 0, // Optional.  The read timeout (in seconds).  Default: 0
                'retry_interval' => 0, // Optional.  The delay (in milliseconds) between reconnection attempts.  Default: 0
                'tcp_keepalive' => 0, // Optional.  The TCP-keepalive timeout (in seconds) of the connection.  Default: 0
                'lazy' => null, // Optional.  Enables or disables lazy connections to the backend.  Default: null (not lazy)
                'cluster' => false, // Optional.  Enables or disables Redis cluster.  Alias: redis_cluster.  Default: false
                'sentinel' => null, // Optional.  The master name connected to the sentinels.  Aliases: redis_sentinel, sentinel_master.  Default: null
                'dbindex' => 0, // Optional.  The database index to select.  Default: 0
                'failover' => 'none', // Optional.  Cluster failover: none, error, distribute or slaves.  Default: none
                'ssl' => null, // Optional.  SSL context options.  See https://php.net/context.ssl.  Default: null
                'cluster_command_timeout' => 0, // Optional.  Command timeout for \Relay\Cluster.  Default: 0
                'cluster_relay_context' => [], // Optional.  Context options for \Relay\Cluster.  Default: []
                
                // Cache Config
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: 0
                'marshaller' => null, // Optional : a marshaller type name, or ['type' => ..., 'options' => [...]].  See Marshallers.  Default: Symfony's DefaultMarshaller
                'logger' => null, // Optional : a PSR-3 logger service name from the container.  See Logging.  Default: no logging
            ],
        ],
    ],
];

Docs: Redis Cache Adapter

Redis Tag Aware

The same as the Redis adapter, with built-in support for tag-based invalidation. It takes the same connection options as the Redis adapter. If you pass in your own client service, it must not have phpredis or Relay compression turned on. Use the deflate marshaller for compression instead.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'RedisTagAware',
            'options' => [
                'client' => 'service-name', // Redis service name.  Will be pulled from the container.
                'dsn' => 'redis://[pass@][ip|host|socket[:port]][/db-index]', // Dsn for connections.

                // Connection options are the same as the Redis adapter.

                // Cache Config
                'namespace' => '', // Optional : a string prefixed to the keys of the items.
                'defaultLifetime' => 0, // Optional : the default lifetime (in seconds) for cache items.  Default: 0
                'marshaller' => 'deflate', // Optional : a marshaller type name, or ['type' => ..., 'options' => [...]].  See Marshallers
                'logger' => null, // Optional : a PSR-3 logger service name from the container.  See Logging.  Default: no logging
            ],
        ],
    ],
];

Docs: Cache Invalidation

Tag Aware

This adapter adds tag-based invalidation to any other cache service. Tags can be stored in the same pool as the items, or in a separate, faster pool.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'TagAware',
            'options' => [
                'itemsPool' => 'service-name', // Required : the cache service that stores the items.
                'tagsPool' => 'service-name', // Optional : the cache service that stores the tags.  Default: the items pool
                'knownTagVersionsTtl' => 0.15, // Optional : how long (in seconds) tag versions are trusted without checking the tags pool.  Default: 0.15
                'logger' => null, // Optional : a PSR-3 logger service name from the container.  See Logging.  Default: no logging
            ],
        ],
    ],
];

Docs: Cache Invalidation

Traceable

This adapter wraps another cache service and records every call made to it: the method, start and end times, hits and misses. Read the records with getCalls() and clear them with clearCalls(). Useful for debugging, tests or collecting your own metrics.

If the wrapped service is tag aware, a TraceableTagAwareAdapter is returned, so invalidateTags() keeps working (and is recorded too).

Calls are kept in memory until clearCalls() is called, so call it regularly in long-running processes such as queue workers.

<?php

return [
    'cache' => [
        'default' => [  
            'type' => 'Traceable',
            'options' => [
                'pool' => 'service-name', // Required : the cache service to wrap.  Pulled from the container.
            ],
        ],
    ],
];

Logging

Symfony's cache adapters don't throw when the backend fails. If Redis is down, a value can't be unserialized, or a save fails, the adapter returns a cache miss or false and carries on. The only place those failures are reported is the adapter's logger, as warnings. The adapter also logs its stampede protection (locks acquired, waited for or timed out) at the info level.

To log them, set the optional logger option to the name of a PSR-3 logger service in your container. Leave it out and nothing is logged. Any PSR-3 logger works; for Monolog, blazon/psr11-monolog provides PSR-11 factories.

<?php

return [
    'cache' => [
        'default' => [
            'type' => 'redis',
            'options' => [
                'dsn' => 'redis://localhost',
                'logger' => 'my-logger-service', // Optional : a PSR-3 logger service name from the container
            ],
        ],
    ],
];

The logger option is supported by the APCu, Array, DoctrineDbal, Filesystem, FilesystemTagAware, Memcached, PDO, PhpFiles, Psr16, Redis, RedisTagAware and TagAware adapters. The Chain, Null, PhpArray, Proxy and Traceable adapters don't log; set the logger on the pools they wrap instead.

Marshallers

A marshaller turns cache values into strings for storage, and back again. The APCu, DoctrineDbal, Filesystem, FilesystemTagAware, Memcached, PDO, Redis and RedisTagAware adapters take a marshaller option, set in one of two ways:

<?php

// A type name: a service name in your container, a short name below, or the class name of your own
// factory implementing Blazon\PSR11SymfonyCache\Marshaller\MarshallerFactoryInterface
'marshaller' => 'deflate',

// A type with options, like an adapter's config
'marshaller' => [
    'type' => 'sodium',
    'options' => [
        'decryptionKeys' => [$key],
        'marshaller' => 'deflate', // Marshallers that wrap another marshaller take the same type name or array
    ],
],

If no marshaller is set, Symfony uses its DefaultMarshaller.

Docs: Marshalling (Serializing) Data

Default

Serializes values with PHP's serialize(), or with igbinary when useIgbinarySerialize is true.

'marshaller' => [
    'type' => 'default',
    'options' => [
        'useIgbinarySerialize' => false, // Optional : true to serialize with igbinary (v3.1.6 or later).  Default: false
        'throwOnSerializationFailure' => false, // Optional : throw instead of skipping values that cannot be serialized.  Default: false
    ],
],

Deflate

Compresses values with gzdeflate(). Requires the zlib extension. Values stored without compression can still be read, so it can be turned on for an existing cache.

'marshaller' => [
    'type' => 'deflate',
    'options' => [
        'marshaller' => 'default', // Optional : the marshaller to compress the output of.  Default: default
    ],
],

Sodium

Encrypts values with libsodium. Requires the sodium extension.

'marshaller' => [
    'type' => 'sodium',
    'options' => [
        // Required : the key at index 0 encrypts and decrypts values.  Add older keys after it to keep reading values
        // while you rotate keys.  Each key must be generated with sodium_crypto_box_keypair().
        'decryptionKeys' => [$key],
        'marshaller' => 'default', // Optional : the marshaller to encrypt the output of.  Default: default
    ],
],

Tag Aware Marshaller

Splits tags out of stored values so they can be read separately. RedisTagAwareAdapter always wraps its marshaller in this one, so it is rarely needed in config.

'marshaller' => [
    'type' => 'tagaware',
    'options' => [
        'marshaller' => 'default', // Optional : the marshaller to wrap.  Default: default
    ],
],

Upgrading from 1.x

  • The minimum versions are now PHP 8.4 and symfony/cache 8.1.
  • The Doctrine adapter type has been removed. Symfony removed DoctrineAdapter in 6.0.
  • The Couchbase adapter type has been removed. Symfony removed CouchbaseBucketAdapter in 8.0, and its replacement, CouchbaseCollectionAdapter, requires the Couchbase 3.x extension, which no longer builds on PHP 8.4 without patching. If you need Couchbase, use Symfony's adapter directly with a patched extension, or register your own adapter in the container.
  • The PDO adapter no longer accepts a Doctrine DBAL connection. Pass a PDO instance or a DSN, or switch to the new DoctrineDbal adapter type.
  • Redis connection options now match Symfony's RedisAdapter::createConnection() options:
    • compression has been removed. Symfony does not support it as a connection option.
    • class no longer defaults to \Redis. Symfony picks \Redis, \Relay\Relay or \Predis\Client, in that order, depending on what is installed.
    • Options you leave out now use Symfony's defaults instead of this package's. For example, lazy defaults to null.
    • New options: auth, cluster, sentinel, dbindex, failover, ssl, cluster_command_timeout and cluster_relay_context. redis_cluster, redis_sentinel and sentinel_master are accepted as aliases.
  • Memcached connection options:
    • Options you leave out now default to Symfony's and the extension's values. This fixes connecting with only a DSN, which failed because the old server_failure_limit default of 0 is rejected by the extension.
    • New options: persistent_id, username and password (SASL), and socket_send_size.
    • hash, serializer and distribution take a name. compression_type takes a Memcached::COMPRESSION_* constant.
    • distribution and hash only apply with libketama_compatible => false. libketama mode, which is on by default, sets its own distribution and hash.
    • dsn can be an array of DSNs.
  • Some options have been renamed to match Symfony. Rename these keys in your config: the old names are no longer read, and are silently ignored, so the adapter falls back to the default value.

    AdapterOld optionNew option
    Chain, DoctrineDbal, Memcached, PDO, Redis, RedisTagAwaremaxLifetimedefaultLifetime
    ArraystoreSerializeddeepClone

    The Array adapter still has a maxLifetime option. It is a separate Symfony setting (the maximum lifetime of the whole cache) and has not been renamed.

  • The Array adapter has a new clock option, which takes a PSR-20 clock service.
  • The PhpFiles adapter has a new appendOnly option.
  • New optional logger option, taking a PSR-3 logger service name, for the adapters that support logging.
  • New Psr16CacheFactory, for a PSR-16 simple cache built from the same configuration.
  • The PDO adapter's db_data_col now defaults to item_data, matching Symfony. The old item_id default could not work, because it used the same column as db_id_col.
  • New adapter types: DoctrineDbal, FilesystemTagAware, Null, Psr16, RedisTagAware, TagAware and Traceable.
  • New marshaller support. Every adapter that stores serialized values (APCu, DoctrineDbal, Filesystem, FilesystemTagAware, Memcached, PDO, Redis and RedisTagAware) takes a marshaller option. Use the deflate marshaller for compression in place of the old Redis compression option.

These docs, including the code samples, are licensed under a Creative Commons BY-SA 3.0 license.