Skip to content

Instantly share code, notes, and snippets.

@u-mulder
Last active Sep 11, 2017
Embed
What would you like to do?
Bitrix tagged caching
<?php
// Source example comes from https://dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=43&LESSON_ID=2978
$cacheTime = 10;
$cacheId = 'cache_id_comes_here';
$cacheDir = '/some_tag_cache/subsubdir';
/* D7 version */
$cache = Bitrix\Main\Data\Cache::createInstance();
if ($cache->initCache($cacheTime, $cacheId, $cacheDir))
{
echo 'Values are taken from cache: <br />';
$result = $cache->getVars();
}
elseif ($cache->startDataCache())
{
echo 'Values will be selected: <br />';
$result = [];
$dbItems = CIBlockElement::GetList(
array('SORT' => 'ASC'),
array(
'IBLOCK_ID' => 1,
'ACTIVE' => 'Y',
),
false,
['nTopCount' => 2],
['ID', 'NAME', 'IBLOCK_ID']
);
$GLOBALS['CACHE_MANAGER']->StartTagCache($cacheDir);
while ($row = $dbItems->Fetch()) {
$GLOBALS['CACHE_MANAGER']->RegisterTag('iblock_id_' . $row['IBLOCK_ID']);
$result[] = $row;
}
$GLOBALS['CACHE_MANAGER']->EndTagCache();
$cache->endDataCache($result);
}
/* Old core version */
$cache = new CPHPCache();
if ($cache->InitCache($cacheTime, $cacheId, $cacheDir))
{
echo 'Values are taken from cache: <br />';
$result = $cache->GetVars();
}
elseif($cache->StartDataCache())
{
echo 'Values will be selected: <br />';
$result = [];
$dbItems = CIBlockElement::GetList(
array('SORT' => 'ASC'),
array(
'IBLOCK_ID' => 1,
'ACTIVE' => 'Y',
),
false,
['nTopCount' => 4],
['ID', 'NAME', 'IBLOCK_ID']
);
$GLOBALS['CACHE_MANAGER']->StartTagCache($cacheDir);
while ($row = $dbItems->Fetch()) {
$GLOBALS['CACHE_MANAGER']->RegisterTag('iblock_id_' . $row['IBLOCK_ID']);
$result[] = $row;
}
/* Don't know what this line means, though it's still working without it */
$GLOBALS['CACHE_MANAGER']->RegisterTag('iblock_id_new');
$GLOBALS['CACHE_MANAGER']->EndTagCache();
$cache->EndDataCache($result);
}
echo'<pre>Result is: ',print_r($result),'</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment