Frequently needed lists for dropdown lists and for displaying values. To this, I use this concept of dictionaries. Will how correct such a solution is:
Dictionary class
class CmdMineDictionary{
private const CACHE_KEY_LIST = 'CmdMineDictionaryList';
public static function getList(): array
{
return \Yii::$app->cache->getOrSet(
self::CACHE_KEY_LIST,
function () {
return ArrayHelper::map(
CmdMine::find()
->select([
'id' => 'id',
'name' => 'name_ru',
])
->orderBy([
'name_ru' => SORT_ASC,
])
->asArray()
->all()
,
'id',
'name'
);
}
);
}
public static function clearCache(): void
{
\Yii::$app->cache->delete(self::CACHE_KEY_LIST);
}
}
To model add reseting cache on update
class CmdMine extends BaseCmdMine
{
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
CmdMineDictionary::clearCache();
}
public function afterDelete()
{
parent::afterDelete();
CmdMineDictionary::clearCache();
}
}