Skip to content

Instantly share code, notes, and snippets.

@shoman4eg
Last active November 23, 2017 07:21
Show Gist options
  • Save shoman4eg/97b7f06cc94e0b7951a75c75682b53f8 to your computer and use it in GitHub Desktop.
Save shoman4eg/97b7f06cc94e0b7951a75c75682b53f8 to your computer and use it in GitHub Desktop.
Bitrix cache function from laravel
<?php
namespace Newkaliningrad\Tools;
use Bitrix\Main\Data\Cache as BxCache;
use Bitrix\Main\Type\DateTime;
use Closure;
class Cache
{
const CACHE_PATH = '/cache/path/';
/**
* @param $key
* @param \DateTime|DateTime|int $minutes
* @param Closure $callback
* @param null $path
* @return mixed
*/
public static function remember($key, $minutes, Closure $callback, $path = null)
{
$cachePath = ($path === null) ? self::CACHE_PATH : $path;
$data = null;
$cache = BxCache::createInstance();
$duration = self::getSeconds($minutes);
if ($cache->initCache($duration, $key, $cachePath)) {
$vars = $cache->getVars();
$data = $vars['data'];
} elseif ($cache->startDataCache()) {
$data = $callback();
$cache->endDataCache(["data" => $data]);
}
return $data;
}
public static function getSeconds($duration)
{
if ($duration instanceof \DateTime || $duration instanceof DateTime) {
$now = new \DateTime();
$duration = abs($duration->getTimestamp() - $now->getTimestamp());
} else {
$duration *= 60;
}
return (int)($duration * 60) > 0 ? $duration : null;
}
}
// Использование
$data = Cache::remember('cache-key', 30, function () {
return ElementTable::getList(['filter' => ['IBLOCK_ID' => 1]])->fetchAll();
});
var_dump($data);
@sidigi
Copy link

sidigi commented Nov 23, 2017

Как насчёт тегов?

public static function remember($key, $minutes, Closure $callback, $tags = null,  $path = null)
    {
        $cachePath = ($path === null) ? self::CACHE_PATH : $path;
        $data = null;
        $cache = BxCache::createInstance();
        $duration = self::getSeconds($minutes);
        if ($cache->initCache($duration, $key, $cachePath)) {
            $vars = $cache->getVars();
            $data = $vars['data'];
        } elseif ($cache->startDataCache()) {
            if (isset($tags)){

                if (!is_array($tags))
                    $tags = [$tags];

                $tagCache = new \Bitrix\Main\Data\TaggedCache();

                foreach ($tags as $tag)
                    $tagCache->startTagCache($cachePath);

                $data = $callback();

                foreach ($tags as $tag)
                    $tagCache->registerTag($tag);

                $tagCache->endTagCache();
            }else{
                $data = $callback();
            }

            if (is_null($data)) {
                $cache->abortDataCache();
                return;
            }

            $cache->endDataCache(["data" => $data]);
        }

        return $data;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment