Skip to content

Commit

Permalink
Cache results in static variable to not ask cache several times per r…
Browse files Browse the repository at this point in the history
…equest - #171
  • Loading branch information
bethrezen committed Feb 24, 2015
1 parent 427d002 commit 25da19a
Showing 1 changed file with 24 additions and 17 deletions.
41 changes: 24 additions & 17 deletions application/components/Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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];
}

/**
Expand Down

0 comments on commit 25da19a

Please sign in to comment.