Skip to content
This repository has been archived by the owner on Oct 18, 2023. It is now read-only.

Commit

Permalink
Performance - Inefficient caching on related skus. (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
bibliophileaxe authored and malachy-mcconnell committed Sep 10, 2018
1 parent 6bd6544 commit cb00e7a
Showing 1 changed file with 8 additions and 34 deletions.
42 changes: 8 additions & 34 deletions modules/sku/src/AcmSkuLinkedSku.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,60 +83,34 @@ public function __construct(APIWrapper $api_wrapper, CacheBackendInterface $cach
* All linked skus of given type.
*/
public function getLinkedskus(SKU $sku, $type = LINKED_SKU_TYPE_ALL) {
$linked_skus = [];

// Cache key is like - 'acm_sku:linked_skus:123'.
$cache_key = 'acm_sku:linked_skus:' . $sku->id();

// Cache key is like - 'acm_sku:linked_skus:123:LINKED_SKU_TYPE_ALL'.
$cache_key = 'acm_sku:linked_skus:' . $sku->id() . ':' . $type;
// Get cached data.
$cache = $this->cache->get($cache_key);

// If already cached.
if ($cache) {
// If only for specific type like cross_sell/upsell/related.
if (isset($cache->data[$type])) {
return $cache->data[$type];
}
elseif ($type == LINKED_SKU_TYPE_ALL && isset($cache->data[LINKED_SKU_TYPE_RELATED]) && isset($cache->data[LINKED_SKU_TYPE_CROSSSELL]) && isset($cache->data[LINKED_SKU_TYPE_UPSELL])) {
// Returning everything in case of 'all' and all keys set.
return $cache->data;
}
return $cache->data;
}

$data = [];
try {
// Get linked skus and set the cache.
$linked_skus = $this->apiWrapper->getLinkedskus($sku->getSku(), $type);

// If cache is set already and we just fetching info of perticular type,
// just updating the existing cache.
if ($type != LINKED_SKU_TYPE_ALL && $cache) {
$cache->data[$type] = $linked_skus[$type];
$linked_skus = $cache->data;
}
elseif ($type != LINKED_SKU_TYPE_ALL && !$cache) {
$linked_skus = [$type => $linked_skus[$type]];
}

$data = $type != LINKED_SKU_TYPE_ALL ? $linked_skus[$type] : $linked_skus;
// Set the cache.
if ($cache_lifetime = $this->configFactory->get('acm_sku.settings')->get('linked_skus_cache_max_lifetime')) {
$cache_lifetime += \Drupal::time()->getRequestTime();
$this->cache->set($cache_key, $linked_skus, $cache_lifetime, ['acm_sku:' . $sku->id()]);
$this->cache->set($cache_key, $data, $cache_lifetime, ['acm_sku:' . $sku->id()]);
}

// Return the data.
return $type != LINKED_SKU_TYPE_ALL ? $linked_skus[$type] : $linked_skus;
}
catch (\Exception $e) {
// If something bad happens, log the error.
$this->loggerFactory->get('acm_sku')->emergency('Unable to get the @linked_sku_type linked skus for @sku : @message', [
'@linked_sku_type' => $type,
'@sku' => $sku->getSku(),
'@message' => $e->getMessage(),
]
);
]);
}

return $linked_skus;
return $data;
}

}

0 comments on commit cb00e7a

Please sign in to comment.