Bitrix D7 — кэширование выборки (Cache + TaggedCache)
Как кешировать результат тяжелой выборки через Bitrix\\Main\\Data\\Cache с поддержкой сброса по тегам.
use Bitrix\Main\Loader;
use Bitrix\Main\Data\Cache;
use Bitrix\Main\Application;
use Bitrix\Iblock\Elements\ElementCatalogTable;
Loader::includeModule('iblock');
$cacheTtl = 600;
$cacheId = 'catalog_top10';
$cacheDir = '/catalog/top';
$cache = Cache::createInstance();
if ($cache->initCache($cacheTtl, $cacheId, $cacheDir)) {
$items = $cache->getVars();
} elseif ($cache->startDataCache()) {
$taggedCache = Application::getInstance()->getTaggedCache();
$taggedCache->startTagCache($cacheDir);
$taggedCache->registerTag('iblock_id_5'); // сброс при изменении ИБ 5
$items = [];
$res = ElementCatalogTable::getList([
'select' => ['ID', 'NAME', 'PRICE.VALUE'],
'filter' => ['IBLOCK_ID' => 5, 'ACTIVE' => 'Y'],
'order' => ['SORT' => 'ASC'],
'limit' => 10
]);
while ($row = $res->fetch()) {
$items[] = $row;
}
$taggedCache->endTagCache();
$cache->endDataCache($items);
}
foreach ($items as $it) {
echo $it['NAME'] . ' — ' . $it['PRICE_VALUE'] . '<br>';
}