Last active
November 23, 2017 07:21
-
-
Save shoman4eg/97b7f06cc94e0b7951a75c75682b53f8 to your computer and use it in GitHub Desktop.
Bitrix cache function from laravel
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 | |
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Как насчёт тегов?