Метод getItem класса Cache
Метод getItem класса Cache возвращает объект CacheItem для указанного ключа.
Первым параметром передаётся ключ элемента кэша в виде строки.
Метод не выбрасывает исключение, если элемент отсутствует: в этом случае возвращается объект CacheItem с пустым значением.
Чтобы понять, был ли элемент найден в кэше, у полученного объекта вызывают метод isHit.
Синтаксис
public function getItem(string $key): CacheItemInterface
Пример
Давайте получим элемент кэша по ключу 'user' и проверим, был ли он найден:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\Cache\CacheInterface;
class CacheController extends AbstractController
{
#[Route('/cache', name: 'cache_index')]
public function index(CacheInterface $cache): Response
{
$item = $cache->getItem('user');
$res = $item->isHit();
return new Response(var_export($res, true));
}
}
?>
Результат выполнения кода:
false
Пример
Давайте сначала сохраним значение в кэш, а затем получим его через getItem:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\Cache\CacheInterface;
class CacheController extends AbstractController
{
#[Route('/cache', name: 'cache_index')]
public function index(CacheInterface $cache): Response
{
$item = $cache->getItem('user');
$item->set('abcde');
$cache->save($item);
$item = $cache->getItem('user');
$res = $item->get();
return new Response($res);
}
}
?>
Результат выполнения кода:
"abcde"
Пример
Давайте получим несуществующий элемент и подставим значение по умолчанию:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\Cache\CacheInterface;
class CacheController extends AbstractController
{
#[Route('/cache', name: 'cache_index')]
public function index(CacheInterface $cache): Response
{
$item = $cache->getItem('article');
if (!$item->isHit()) {
$item->set('hello');
$cache->save($item);
}
return new Response($item->get());
}
}
?>
Результат выполнения кода:
"hello"