The Cache component stores the results of expensive operations in many backends: files, Redis, Valkey, Memcached, databases, etc. Symfony 8.2 makes it simpler to choose that backend, makes cache tags faster when using a database and reports a kind of failure that went unnoticed until now.
Configuring the App Cache with a DSN
Changing the backend of the application cache requires two options: the
adapter (framework.cache.app) and the matching provider (e.g.
default_redis_provider). The adapter is part of your application config, so
moving to a platform that provides Memcached instead of Redis means changing
code, not only environment variables.
Symfony 8.2 adds a default_provider option that takes a DSN and deduces the
adapter of cache.app from it:
1 2 3 4
# config/packages/cache.yaml
framework:
cache:
default_provider: '%env(APP_CACHE_DSN)%'
1 2 3 4 5
# .env
APP_CACHE_DSN=redis://localhost
# the same config works when the platform provides another backend
# APP_CACHE_DSN=memcached://localhost
The supported schemes are redis[s], valkey[s], memcached,
couchbase and the PDO ones (mysql, pgsql, sqlite, oci and
sqlsrv). The cache.system pool is not affected: it keeps storing its
data in files that OPcache can load. Custom pools that define a provider and
no adapter also deduce the adapter from the DSN.
In standalone PHP applications, use the new createAdapter() method:
1 2 3 4 5
use Symfony\Component\Cache\Adapter\AbstractAdapter;
$connection = AbstractAdapter::createConnection($_ENV['APP_CACHE_DSN']);
// returns a RedisAdapter, a MemcachedAdapter, a PdoAdapter, etc.
$cache = AbstractAdapter::createAdapter($connection);
Native Cache Tags for PDO
PdoAdapter stores cache items in a database table, but it knows nothing
about tags. To use them you had to wrap it with the generic TagAwareAdapter,
which stores a version number per tag as regular cache items and fetches them
every time you read a tagged item.
Symfony 8.2 adds PdoTagAwareAdapter, which saves the tags of each item in a
second table. Reading an item no longer needs any tag lookup, and invalidating
tags is a single DELETE query. In Symfony applications, use it via the new
cache.adapter.pdo_tag_aware adapter:
1 2 3 4 5 6 7
# config/packages/cache.yaml
framework:
cache:
default_pdo_provider: 'sqlite:%kernel.project_dir%/var/cache.db'
pools:
products.cache:
adapter: cache.adapter.pdo_tag_aware
The pool is tag-aware without setting tags: true, so you can inject it with
the TagAwareCacheInterface $productsCache type-hint. You must name this
adapter explicitly: a pool that deduces its adapter from a PDO DSN uses
PdoAdapter, and tags: true wraps it with the generic TagAwareAdapter.
In standalone PHP applications, create the adapter yourself:
1 2 3 4 5 6
use Symfony\Component\Cache\Adapter\PdoTagAwareAdapter;
$cache = new PdoTagAwareAdapter('pgsql:host=127.0.0.1;dbname=app', options: [
'db_username' => 'db_user',
'db_password' => 'db_password',
]);
The adapter creates its two tables (cache_items and cache_tags by
default) when they don't exist. Like PdoAdapter, it takes a PDO instance
or a PDO DSN, but not Doctrine DBAL connections or URLs (sqlite:///...).
Detecting Failed Saves
When CacheInterface::get() doesn't find an item, it calls your callback,
saves the result and returns it. If the backend fails to save the value (e.g.
Redis is down or the disk is full), you still get the computed value, with no
way to know that it wasn't stored. That's fine for most caches, but not when the
value is costly to compute or when something else relies on it being stored.
In Symfony 8.2, the $metadata argument of get() reports those failures
with the new ItemInterface::METADATA_SAVE_FAILED key:
1 2 3 4 5 6 7 8 9 10 11 12
use Symfony\Contracts\Cache\ItemInterface;
$rates = $this->cache->get('exchange_rates', function (ItemInterface $item): array {
$item->expiresAfter(3600);
// a slow and metered API call
return $this->exchangeRateApi->fetchRates();
}, null, $metadata);
if (isset($metadata[ItemInterface::METADATA_SAVE_FAILED])) {
$this->logger->warning('Exchange rates were fetched but not cached.');
}
The key is only defined when the save failed, so check it with isset().
It's reported by the adapters of the Cache component and by any class using
CacheTrait, and it requires symfony/cache-contracts 3.8 or newer.
The Scheduler component already relies on it: the checkpoint that tracks the
last run of each schedule now detects failed saves with any CacheInterface
implementation, not only with PSR-6 cache pools.