From 25da19afcd376c81013c702e03e156c78f33289b Mon Sep 17 00:00:00 2001 From: bethrezen Date: Tue, 24 Feb 2015 11:04:36 +0300 Subject: [PATCH] Cache results in static variable to not ask cache several times per request - #171 --- application/components/Helper.php | 41 ++++++++++++++++++------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/application/components/Helper.php b/application/components/Helper.php index 8e9b2371c..9b7f06011 100644 --- a/application/components/Helper.php +++ b/application/components/Helper.php @@ -8,8 +8,13 @@ use yii\helpers\ArrayHelper; use Imagine\Image\ManipulatorInterface; +/** + * Universal helper for common use cases + * @package app\components + */ class Helper { + private static $modelMaps = []; /** * Get all model records as array key => value. * @param string $className @@ -22,25 +27,27 @@ public static function getModelMap($className, $keyAttribute, $valueAttribute, $ { /** @var ActiveRecord $className */ $cacheKey = 'Map: ' . $className::tableName() . ':' . $keyAttribute . ':' . $valueAttribute; - $result = $useCache ? Yii::$app->cache->get($cacheKey) : false; - if ($result === false) { - $result = ArrayHelper::map($className::find()->all(), $keyAttribute, $valueAttribute); - if ($useCache) { - Yii::$app->cache->set( - $cacheKey, - $result, - 86400, - new TagDependency( - [ - 'tags' => [ - \devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag($className), - ], - ] - ) - ); + if (isset(Helper::$modelMaps[$cacheKey]) === false) { + Helper::$modelMaps[$cacheKey] = $useCache ? Yii::$app->cache->get($cacheKey) : false; + if (Helper::$modelMaps[$cacheKey] === false) { + Helper::$modelMaps[$cacheKey] = ArrayHelper::map($className::find()->all(), $keyAttribute, $valueAttribute); + if ($useCache) { + Yii::$app->cache->set( + $cacheKey, + Helper::$modelMaps[$cacheKey], + 86400, + new TagDependency( + [ + 'tags' => [ + \devgroup\TagDependencyHelper\ActiveRecordHelper::getCommonTag($className), + ], + ] + ) + ); + } } } - return $result; + return Helper::$modelMaps[$cacheKey]; } /**