Метод saveDeferred
Метод saveDeferred класса Cache
откладывает сохранение элемента кеша до момента
вызова метода commit. Первым параметром
передаётся объект CacheItemInterface,
который нужно сохранить. В отличие от метода
save, запись не выполняется сразу, а
накапливается во внутреннем буфере. Это удобно,
когда нужно записать сразу несколько элементов
одной пачкой.
Синтаксис
public function saveDeferred(CacheItemInterface $item): bool
Пример
Давайте отложим запись одного элемента и затем
применим её через commit:
<?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 ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index')]
public function index(CacheInterface $cache): Response
{
$item = $cache->getItem('article_key');
$item->set('article');
$res = $cache->saveDeferred($item);
var_dump($res);
$cache->commit();
return new Response('done');
}
}
?>
Результат выполнения кода:
true
Пример
Давайте отложим запись нескольких элементов и применим их одной пачкой:
<?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 ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index')]
public function index(CacheInterface $cache): Response
{
$keys = ['a', 'b', 'c', 'd', 'e'];
foreach ($keys as $key) {
$item = $cache->getItem($key);
$item->set('hello');
$cache->saveDeferred($item);
}
$cache->commit();
return new Response('done');
}
}
?>
Результат выполнения кода:
"done"
Пример
Давайте проверим, что до вызова commit
элемент ещё не записан в кеш:
<?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 ArticleController extends AbstractController
{
#[Route('/article', name: 'article_index')]
public function index(CacheInterface $cache): Response
{
$item = $cache->getItem('user_key');
$item->set('user');
$cache->saveDeferred($item);
$check = $cache->hasItem('user_key');
var_dump($check);
$cache->commit();
$check = $cache->hasItem('user_key');
var_dump($check);
return new Response('done');
}
}
?>
Результат выполнения кода:
false
true