Адаптер ApcuAdapter
Адаптер ApcuAdapter представляет собой реализацию PSR-6 кеша,
которая хранит элементы в оперативной памяти с помощью расширения APCu.
Он не требует внешнего сервера и работает в рамках одного процесса PHP.
Первым параметром конструктора передаётся пространство имён (namespace),
вторым - время жизни элементов по умолчанию, третьим - версия кеша.
Адаптер удобен для кеширования данных, которые часто запрашиваются
и быстро устаревают.
Синтаксис
new ApcuAdapter(string $namespace = '', int $defaultLifetime = 0, string $version = null)
Пример
Давайте создадим адаптер и сохраним в кеш строку 'article':
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Cache\Adapter\ApcuAdapter;
use Symfony\Component\Routing\Attribute\Route;
class CacheController extends AbstractController
{
#[Route('/cache/apcu', name: 'cache_apcu')]
public function index(): Response
{
$cache = new ApcuAdapter('app_cache', 3600);
$item = $cache->getItem('article_key');
$item->set('article');
$cache->save($item);
$res = $cache->getItem('article_key')->get();
return new Response($res);
}
}
?>
Результат выполнения кода:
"article"
Пример
Давайте проверим наличие элемента в кеше с помощью метода hasItem:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Cache\Adapter\ApcuAdapter;
use Symfony\Component\Routing\Attribute\Route;
class CacheController extends AbstractController
{
#[Route('/cache/apcu/has', name: 'cache_apcu_has')]
public function has(): Response
{
$cache = new ApcuAdapter('app_cache', 3600);
$item = $cache->getItem('user_key');
$item->set('user');
$cache->save($item);
$res = $cache->hasItem('user_key') ? 'yes' : 'no';
return new Response($res);
}
}
?>
Результат выполнения кода:
"yes"
Пример
Давайте удалим элемент из кеша методом deleteItem и проверим результат:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Cache\Adapter\ApcuAdapter;
use Symfony\Component\Routing\Attribute\Route;
class CacheController extends AbstractController
{
#[Route('/cache/apcu/delete', name: 'cache_apcu_delete')]
public function delete(): Response
{
$cache = new ApcuAdapter('app_cache', 3600);
$item = $cache->getItem('hello_key');
$item->set('hello');
$cache->save($item);
$cache->deleteItem('hello_key');
$res = $cache->hasItem('hello_key') ? 'yes' : 'no';
return new Response($res);
}
}
?>
Результат выполнения кода:
"no"
Смотрите также
-
класс
Cache,
который предоставляет общий интерфейс для работы с кешем -
метод
getItem,
который возвращает элемент кеша по ключу -
метод
save,
который сохраняет элемент кеша -
адаптер
FilesystemAdapter,
который сохраняет кеш в файловой системе