2 Methods to Save Value to Cache in Symfony 8

2 Methods to Save Value to Cache in Symfony 8

Caching plays an important role in improving application performance by reducing repeated computations and unnecessary data fetching. Symfony includes multiple caching APIs, allowing values to be stored and retrieved using different abstraction levels. This tutorial provides 2 methods how to save value to cache in Symfony 8 application.

Method 1 - Cache contracts

One common approach is to use Symfony cache contracts. By injecting CacheInterface, cached values can be accessed through a callback-based mechanism. When a cache key is missing, the callback is executed and its result is stored automatically. This method keeps the code concise and readable.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;

class TestController
{
    #[Route('/')]
    public function index(CacheInterface $cache): Response
    {
        $value = $cache->get('my_cache_key', function (ItemInterface $item): string {
            $item->expiresAfter(30);

            return 'Cached value';
        });

        return new Response($value);
    }
}

Method 2 - PSR-6

Another option is to work directly with the PSR-6 cache implementation by using CacheItemPoolInterface. This approach exposes cache item state, making it possible to explicitly check for cache hits and manually persist values. This technique is useful in scenarios that require greater control over cache behavior or compatibility with PSR-6-compliant libraries.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    #[Route('/')]
    public function index(CacheItemPoolInterface $cache): Response
    {
        $item = $cache->getItem('my_cache_key');
        if (!$item->isHit()) {
            $item->set('Cached value');
            $item->expiresAfter(30);
            $cache->save($item);
        }
        $value = $item->get();

        return new Response($value);
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.