РЕПЕТИТОР математика физика информатика
Для школьников и студентов. Подтягивание пробелов. ЦЭ, ЦТ, ОГЭ, ЕГЭ.
Идет набор на ЛЕТО. Жмите для подробностей:)
821 of 1361 menu

Класс CacheItem

Класс CacheItem представляет собой один элемент кеша. Он хранит значение, ключ, срок жизни и метаданные. Объект этого класса возвращается методом getItem и передаётся в методы save и deleteItem. Через методы get и set читают и записывают значение, через isHit проверяют, было ли значение найдено в кеше, а через expiresAfter и expiresAt задают срок жизни.

Синтаксис

<?php use Symfony\Contracts\Cache\ItemInterface; $item = $cache->getItem('key'); $item->set($value); $item->expiresAfter($seconds); $cache->save($item); ?>

Пример

Давайте создадим элемент кеша, запишем в него строку и сохраним через адаптер ArrayAdapter:

<?php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Routing\Attribute\Route; class CacheController extends AbstractController { #[Route('/cache', name: 'cache_index')] public function index(): Response { $cache = new ArrayAdapter(); $item = $cache->getItem('article'); $item->set('hello'); $cache->save($item); $res = $cache->getItem('article')->get(); return new Response($res); } } ?>

Результат выполнения кода:

hello

Пример

Давайте проверим, найдено ли значение в кеше, с помощью метода isHit:

<?php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Routing\Attribute\Route; class CacheController extends AbstractController { #[Route('/cache-hit', name: 'cache_hit')] public function hit(): Response { $cache = new ArrayAdapter(); $item = $cache->getItem('user'); if (!$item->isHit()) { $item->set('abcde'); $cache->save($item); } $res = $item->get(); return new Response($res); } } ?>

Результат выполнения кода:

abcde

Пример

Давайте зададим срок жизни элемента кеша в секундах через метод expiresAfter:

<?php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Routing\Attribute\Route; class CacheController extends AbstractController { #[Route('/cache-ttl', name: 'cache_ttl')] public function ttl(): Response { $cache = new ArrayAdapter(); $item = $cache->getItem('article'); $item->set('hello'); $item->expiresAfter(3600); $cache->save($item); $res = $item->get(); return new Response($res); } } ?>

Результат выполнения кода:

hello

Пример

Давайте получим ключ элемента через метод getKey и метаданные через метод getMetadata:

<?php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Routing\Attribute\Route; class CacheController extends AbstractController { #[Route('/cache-meta', name: 'cache_meta')] public function meta(): Response { $cache = new ArrayAdapter(); $item = $cache->getItem('article'); $item->set('hello'); $cache->save($item); $res = $item->getKey() . ' ' . $item->getMetadata()['expiry']; return new Response($res); } } ?>

Результат выполнения кода:

article 0

Смотрите также

  • класс CacheItem,
    который представляет элемент кеша
  • метод getItem,
    который возвращает элемент кеша по ключу
  • метод save,
    который сохраняет элемент кеша
  • метод expiresAfter,
    который задаёт срок жизни элемента кеша
Мы используем cookie для работы сайта, аналитики и персонализации. Обработка данных происходит согласно Политике конфиденциальности.
принять все настроить отклонить