Метод isHit
Метод isHit класса CacheItem возвращает true,
если значение было найдено в кэше, и false, если элемента
в кэше нет. Метод не принимает параметров. Его вызывают у объекта,
полученного через метод getItem класса CacheInterface.
Синтаксис
public function isHit(): bool
Пример
Давайте получим элемент из кэша и проверим, было ли значение найдено:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
use SymfonyContractsCacheCacheInterface;
class CacheController extends AbstractController
{
#[Route('/cache', name: 'cache_index')]
public function index(CacheInterface $cache): Response
{
$item = $cache->getItem('article_key');
if ($item->isHit()) {
return new Response('cache hit');
}
return new Response('cache miss');
}
}
?>
Результат выполнения кода при пустом кэше:
cache miss
Пример
Давайте сохраним значение в кэш, а затем проверим его наличие:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
use SymfonyContractsCacheCacheInterface;
class CacheController extends AbstractController
{
#[Route('/cache/save', name: 'cache_save')]
public function save(CacheInterface $cache): Response
{
$item = $cache->getItem('article_key');
$item->set('abcde');
$cache->save($item);
$item = $cache->getItem('article_key');
if ($item->isHit()) {
return new Response($item->get());
}
return new Response('cache miss');
}
}
?>
Результат выполнения кода:
abcde
Пример
Давайте проверим наличие нескольких элементов кэша в цикле:
<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
use SymfonyContractsCacheCacheInterface;
class CacheController extends AbstractController
{
#[Route('/cache/items', name: 'cache_items')]
public function items(CacheInterface $cache): Response
{
$res = [];
foreach (['article', 'user', 'hello'] as $key) {
$item = $cache->getItem($key);
$res[$key] = $item->isHit();
}
return new Response(json_encode($res));
}
}
?>
Результат выполнения кода при пустом кэше:
{"article":false,"user":false,"hello":false}