Caching data with the Symfony CacheItemPoolInterface service

Published on 2023-02-14 • Modified on 2023-02-14

This snippet shows how to cache data with the Symfony CacheItemPoolInterface service. In a previous snippet, we saw how to cache data thanks to the CacheInterface service. It works well, but it gives us little control. For more advanced cases, we can use the CacheItemPoolInterface, for example, if we want to do specific actions if there is a hit or not for a given cache key.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Psr\Cache\CacheItemPoolInterface;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 *
 * @property CacheItemPoolInterface $cacheItemPool
 */
trait Snippet243Trait
{
    public function snippet243(): void
    {
        $cacheItem = $this->cacheItemPool
            ->getItem('my_cache_key')
            ->expiresAfter(\DateInterval::createFromDateString('10 seconds'))
        ;

        if ($cacheItem->isHit()) {
            echo 'There was a hit for the cache key: '.$cacheItem->get();
        } else {
            echo 'No cache hit. Saving cache item.';
            $cacheItem->set('cache_value');
            $this->cacheItemPool->save($cacheItem);
        }

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!