Symfony/Cache is a powerful component used to add cache to your applications. Following the PSR-6 and PSR-16 caching standards, Symfony/Cache is designed for speed and low overhead to make caching faster and more efficient. It's packed with adapters for the most common caching backends and also provides implementations for Symfony's CacheInterface and TagAwareCacheInterface from the symfony/cache-contracts package. Leveraging caching in your applications can greatly improve performance by storing data in a cache for faster future access.
To use symfony/cache, first, you need to install it via composer. Run composer require symfony/cache
. This command installs the symfony/cache package into your project.
Here is an example of how to use the cache component:
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
// The first argument is the namespace, which should be unique per cache pool
// The second argument is the default lifetime of cache items, in seconds
$cache = new FilesystemAdapter('my_cache_namespace', 3600);
// Attempt to fetch the cached value
$value = $cache->get('my_cache_key', function (ItemInterface $item) {
$item->expiresAfter(3600);
// do some expensive computation or fetch data
// and finally return the computed value
return "cached value";
});
echo $value; // Output: "cached value"
In this example, we first create an instance of FilesystemAdapter which represents the cache pool. Next, we attempt to fetch a value from the cache using the get() method. If the value does not exist in the cache, we use a callback function to compute and return the value, which gets stored in the cache.
For detailed usage and examples, you can refer to the official Symfony Cache component documentation by visiting Symfony's official documentation. You can also contribute, report issues and send pull requests in the main Symfony repository. The symfony/cache package follows Symfony's code of conduct and contributing guidelines.