Cache
| Cache pools | |
| Get with callback | |
| Expire times | |
| Clear pools |
Cache pools
A pool is a named storage area for cached values, for example one pool for rendered pages and one for system data. The framework injects the requested pool through the cache interface.
Type hint the CacheInterface in services and let autowiring provide the default application pool. Use separate pools when entries need different lifetimes or clearing rules.
namespace App\Service; use Symfony\Contracts\Cache\CacheInterface; class HomeService { public function __construct(private CacheInterface $cache) { } }
Get with callback
The get method returns the stored value when the key exists and runs the callback only on a miss. The callback builds the fresh value so callers never handle the miss case directly.
Use stable string keys that describe the content, such as homepage. Keep the callback pure and free of output so repeated calls stay safe.
namespace App\Service; use Symfony\Contracts\Cache\CacheInterface; use Symfony\Contracts\Cache\ItemInterface; class HomeService { public function __construct(private CacheInterface $cache) { } public function homepage(): string { return $this->cache->get("homepage", function (ItemInterface $item): string { return "hello"; }); } }
Expire times
Every entry needs a lifetime so stale data disappears on its own. Call expiresAfter on the item with seconds, then return the fresh value from the callback.
Short lifetimes suit fast changing pages while long lifetimes suit reference data. Pick the smallest lifetime that keeps the site fast without showing outdated content.
namespace App\Service; use Symfony\Contracts\Cache\CacheInterface; use Symfony\Contracts\Cache\ItemInterface; class HomeService { public function __construct(private CacheInterface $cache) { } public function homepage(): string { return $this->cache->get("homepage", function (ItemInterface $item): string { $item->expiresAfter(3600); return "hello"; }); } }
Clear pools
Clearing removes stored entries so the next request rebuilds them from source. Clear one named pool after content changes instead of wiping all pools at once.
The application pool holds page data while the system pool holds framework internals. Rebuild the affected page after clearing to confirm fresh content appears.
pools: cache.app: default application pool cache.system: system pool
Next: Sessions
Article author: Arthur Isaev