Skip to content

Commit

Permalink
Introduced separate cache type for navigation
Browse files Browse the repository at this point in the history
  • Loading branch information
diwipl committed Sep 3, 2020
1 parent 7035cf5 commit 986914d
Show file tree
Hide file tree
Showing 21 changed files with 243 additions and 124 deletions.
9 changes: 4 additions & 5 deletions Block/Adminhtml/Category/Tab/FeaturedProducts.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ public function __construct(
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\Json\DecoderInterface $jsonDecoder,
array $data = []
)
{
) {
$this->categoryRepository = $categoryRepository;
$this->productFactory = $productFactory;
$this->coreRegistry = $coreRegistry;
Expand All @@ -52,7 +51,7 @@ protected function _construct()
public function getCategory()
{
$category = $this->coreRegistry->registry('category');
if(!$category){
if (!$category) {
$category = $this->categoryRepository->get(
$this->getRequest()->getParam('id', 2),
$this->getRequest()->getParam('store', 0)
Expand Down Expand Up @@ -162,8 +161,8 @@ protected function _getSelectedFeaturedProducts()
$featuredProducts = $this->getCategory()->getFeaturedProducts();
}

if ($featuredProducts){
if(is_string($featuredProducts)) {
if ($featuredProducts) {
if (is_string($featuredProducts)) {
$featuredProducts = $this->jsonDecoder->decode($featuredProducts);
}

Expand Down
117 changes: 85 additions & 32 deletions Block/Navigation.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

class Navigation extends \Magento\Framework\View\Element\Template implements \Magento\Framework\DataObject\IdentityInterface
{
const CACHE_KEY_PREFIX = 'NAVIGATION_';
const CACHE_GROUP = \MageSuite\Navigation\Model\Cache\Type::TYPE_IDENTIFIER;

const ONE_DAY = 86400;

/**
Expand All @@ -20,15 +23,22 @@ class Navigation extends \Magento\Framework\View\Element\Template implements \Ma
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;

/**
* @var \Magento\Framework\Serialize\SerializerInterface
*/
protected $serializer;

/**
* @var \Magento\Customer\Model\Session
*/
protected $session;

/**
* @var \Magento\Framework\Cache\LockGuardedCacheLoader
*/
protected $lockGuardedCacheLoader;

public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\App\Http\Context $httpContext,
Expand All @@ -37,38 +47,41 @@ public function __construct(
\Magento\Framework\Serialize\SerializerInterface $serializer,
\Magento\Customer\Model\Session $session,
array $data = []
)
{
) {
parent::__construct($context, $data);

$this->httpContext = $httpContext;
$this->navigationBuilder = $navigationBuilder;
$this->storeManager = $storeManager;
$this->serializer = $serializer;
$this->session = $session;
$this->lockGuardedCacheLoader = $context->getLockGuardedCacheLoader();
}

/**
* @return \MageSuite\Navigation\Model\Navigation\Item[]
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getItems() {
public function getItems()
{
$rootCategoryId = $this->storeManager->getStore()->getRootCategoryId();

$buildedNavigation = $this->navigationBuilder->build($rootCategoryId, $this->getNavigationType());

$cacheTags = $this->getNavigationTags($buildedNavigation);

$this->_cache->save($this->serializer->serialize($cacheTags), 'navigation_'.$rootCategoryId.'_'.$this->getNavigationType(), $cacheTags);

return $buildedNavigation;
}

public function getCacheTags()
{
return [\MageSuite\Navigation\Model\Cache\Type::CACHE_TAG];
}

/**
* @return string
*/
public function getNavigationType() {
if($this->getType() == \MageSuite\Navigation\Service\Navigation\Builder::TYPE_MOBILE) {
public function getNavigationType()
{
if ($this->getType() == \MageSuite\Navigation\Service\Navigation\Builder::TYPE_MOBILE) {
return \MageSuite\Navigation\Service\Navigation\Builder::TYPE_MOBILE;
}

Expand All @@ -90,7 +103,10 @@ public function getCacheKeyInfo()
];
}

public function getMobileNavigationEndpointUrl() {


public function getMobileNavigationEndpointUrl()
{
return $this->getUrl('navigation/mobile/index');
}

Expand All @@ -106,37 +122,74 @@ public function getCacheLifetime()
* @return string[]
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function getIdentities(){
$rootCategoryId = $this->storeManager->getStore()->getRootCategoryId();

$cachedTags = $this->_cache->load('navigation_'.$rootCategoryId.'_'.$this->getNavigationType());
public function getIdentities()
{
return [\MageSuite\Navigation\Model\Cache\Type::CACHE_TAG];
}

if($cachedTags) {
return $this->serializer->unserialize($cachedTags);
/**
* Following methods had to be overriden to modify values for
* CACHE_KEY_PREFIX and CACHE_GROUP constants
*/
public function getCacheKey()
{
if ($this->hasData('cache_key')) {
return self::CACHE_KEY_PREFIX . $this->getData('cache_key');
}

$navigationItems = $this->getItems();
$key = $this->getCacheKeyInfo();
$key = array_values($key);
$key = implode('|', $key);
$key = hash('sha1', $key);

return $this->getNavigationTags($navigationItems);
return self::CACHE_KEY_PREFIX . $key;
}

/**
* @param \MageSuite\Navigation\Model\Navigation\Item[] $navigationItems
*/
protected function getNavigationTags(array $navigationItems, $aggregatedTags = [\Magento\Catalog\Model\Category::CACHE_TAG])
protected function _loadCache()
{
if(empty($navigationItems)) {
return $aggregatedTags;
}
$collectAction = function () {
if ($this->hasData('translate_inline')) {
$this->inlineTranslation->suspend($this->getData('translate_inline'));
}

$this->_beforeToHtml();
return $this->_toHtml();
};

foreach($navigationItems as $navigationItem) {
if($navigationItem->hasSubItems()) {
$aggregatedTags = array_merge($aggregatedTags, $this->getNavigationTags($navigationItem->getSubItems(), $aggregatedTags));
if ($this->getCacheLifetime() === null || !$this->_cacheState->isEnabled(self::CACHE_GROUP)) {
$html = $collectAction();
if ($this->hasData('translate_inline')) {
$this->inlineTranslation->resume();
}
return $html;
}
$loadAction = function () {
return $this->_cache->load($this->getCacheKey());
};

$saveAction = function ($data) {
$this->_saveCache($data);
if ($this->hasData('translate_inline')) {
$this->inlineTranslation->resume();
}
};

return (string)$this->lockGuardedCacheLoader->lockedLoadData(
$this->getCacheKey(),
$loadAction,
$collectAction,
$saveAction
);
}

$aggregatedTags = array_merge($aggregatedTags, $navigationItem->getIdentities());
protected function _saveCache($data)
{
if (!$this->getCacheLifetime() || !$this->_cacheState->isEnabled(self::CACHE_GROUP)) {
return false;
}
$cacheKey = $this->getCacheKey();

return array_unique($aggregatedTags);
$this->_cache->save($data, $cacheKey, array_unique($this->getCacheTags()), $this->getCacheLifetime());
return $this;
}
}
}
9 changes: 4 additions & 5 deletions Block/Navigation/ActiveCategory.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,12 @@ public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
array $data = []
)
{
) {
$this->registry = $registry;

parent::__construct($context, $data);
}

public function getActiveCategoryPath()
{
/** @var \Magento\Catalog\Model\Category $currentCategory */
Expand All @@ -28,11 +27,11 @@ public function getActiveCategoryPath()

$categoryPath = $currentCategory->getPath();

return $this->removeRootCategoryFromPath($categoryPath);;
return $this->removeRootCategoryFromPath($categoryPath);
}

private function removeRootCategoryFromPath($categoryPath)
{
return substr($categoryPath, strpos($categoryPath, '/') + 1);
}
}
}
2 changes: 1 addition & 1 deletion Controller/Adminhtml/Category/FeaturedProducts.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ abstract class FeaturedProducts extends \Magento\Backend\App\Action
* @see _isAllowed()
*/
const ADMIN_RESOURCE = 'MageSuite_Navigation::item_list';
}
}
7 changes: 2 additions & 5 deletions Controller/Adminhtml/Category/FeaturedProducts/Grid.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
\Magento\Framework\View\LayoutFactory $layoutFactory
)
{
) {
parent::__construct($context);
$this->resultRawFactory = $resultRawFactory;
$this->layoutFactory = $layoutFactory;
Expand All @@ -36,6 +35,4 @@ public function execute()
)->toHtml()
);
}


}
}
2 changes: 1 addition & 1 deletion Controller/Mobile/Index.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ public function execute()
{
return $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_LAYOUT);
}
}
}
10 changes: 5 additions & 5 deletions Migration/AddIncludeInMobileDefaultValue.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\EntityManager\MetadataPool $metadataPool,
\Psr\Log\LoggerInterface $logger
){
) {
$this->connection = $resourceConnection->getConnection();
$this->storeManager = $storeManager;
$this->logger = $logger;
Expand All @@ -49,7 +49,7 @@ public function execute($includeInMobileAttributeId, $includeInDesktopAttributeI
$storeIds = array_keys($stores);
sort($storeIds);

foreach($storeIds as $storeId){
foreach ($storeIds as $storeId) {
$query = "INSERT IGNORE INTO $categoryEntityIntTable (attribute_id, store_id, $linkField, value)
SELECT
$includeInMobileAttributeId AS attribute_id,
Expand All @@ -60,12 +60,12 @@ public function execute($includeInMobileAttributeId, $includeInDesktopAttributeI
LEFT JOIN $categoryEntityIntTable AS category_int ON category.$linkField = category_int.$linkField
WHERE category_int.attribute_id = $includeInDesktopAttributeId AND store_id = $storeId;";

try{
try {
$this->connection->query($query);
}catch (Exception $e){
} catch (Exception $e) {
$message = sprintf('Error during AddIncludeInMobileDefaultValue::execute(): %s, storeId: %s', $e->getMessage(), $storeId);
$this->logger->warning($message);
}
}
}
}
}
48 changes: 48 additions & 0 deletions Model/Cache/Type.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

namespace MageSuite\Navigation\Model\Cache;

class Type extends \Magento\Framework\Cache\Frontend\Decorator\TagScope
{
const TYPE_IDENTIFIER = 'navigation';
const CACHE_TAG = 'navigation';

/**
* @var \Magento\Framework\Event\Manager
*/
protected $eventManager;

/**
* @var \Magento\Framework\Indexer\CacheContext
*/
protected $cacheContext;

/**
* @param \Magento\Framework\App\Cache\Type\FrontendPool $cacheFrontendPool
*/
public function __construct(
\Magento\Framework\App\Cache\Type\FrontendPool $cacheFrontendPool,
\Magento\Framework\Event\Manager $eventManager,
\Magento\Framework\Indexer\CacheContext $cacheContext
)
{
parent::__construct($cacheFrontendPool->get(self::TYPE_IDENTIFIER), self::CACHE_TAG);
$this->eventManager = $eventManager;
$this->cacheContext = $cacheContext;
}

public function clean($mode = \Zend_Cache::CLEANING_MODE_ALL, array $tags = [])
{
if($mode == \Zend_Cache::CLEANING_MODE_ALL) {
$this->clearFullPageCache();
}

return parent::clean($mode, $tags);
}

public function clearFullPageCache(): void
{
$this->cacheContext->registerTags([self::CACHE_TAG]);
$this->eventManager->dispatch('clean_cache_by_tags', ['object' => $this->cacheContext]);
}
}
Loading

0 comments on commit 986914d

Please sign in to comment.