Last active
September 11, 2017 09:42
-
-
Save u-mulder/730bff329931f978c07d421cd94eab17 to your computer and use it in GitHub Desktop.
Bitrix tagged caching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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