New in Symfony 3.2: Cache improvements
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Symfony is a special cache
adapter that disables the cache (it loses all the items saved on it and it
false for all the read and save operations). This adapter is
mostly useful for tests.
Symfony is very similar to
FilesystemAdapter but it has a better performance when using
OPcache in the server.
The trick is that when items are saved, the new adapter creates a PHP file that
is included during the
fetch() operations. This allows OPcache to cache
those files in its memory. In our benchmarks,
PhpFilesAdapter was 3.5 times
FilesystemAdapter for read operations but a bit slower for write
operations, so it's mostly meant for data that rarely changes.
Symfony allows to use any
DBAL-compatible database as the storage of your cache. Its implementation
heavily borrows from
PdoSessionHandler. For example, to create a SQLite-based
cache, execute the following:
1 2 3 4 5
use Symfony\Component\Cache\Adapter\PdoAdapter; $dbFilePath = tempnam(sys_get_temp_dir(), 'sf_sqlite_cache'); $pool = new PdoAdapter('sqlite:'.$dbFilePath); $pool->createTable();
Tag-based invalidation is one of the mechanisms provided by Symfony to invalidate caches, which is the process of removing all cached items related to a change in the state of your model.
In Symfony 3.2, a new
Symfony interface allow
to transform any cache adapter into a tag-aware adapter.
The constructor of the
TagAwareAdapter class accepts two arguments: the
first one is the cache adapter used to store the items and the second optional
argument is the adapter used to cache the tags. This allows you for example to
use a file system or database cache for storing large items and to use a Redis
cache for the tags to have ultra-fast invalidation checks:
1 2 3 4 5 6 7 8
use Symfony\Component\Cache\Adapter\TagAwareAdapter; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Component\Cache\Adapter\RedisAdapter; $cache = new TagAwareAdapter( new FilesystemAdapter(), new RedisAdapter('redis://localhost') );
The FrameworkBundle now includes a
cache:pool:clear command that takes as
argument one or more service names. These services are the cache pools to clear
or the Cache clearer services to invoke:
$ ./bin/console cache:pool:clear app.cache app.cache.products
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.