我写了一个cron作业,该作业检查了直接在数据库中进行的库存数量变化,因此绕过了将处理的洋红色核心,该核心将处理该缓存。
我希望能够以以下方式使用对象管理器:
public function clearCacheforProduct($productID) {
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$cacheManager = $objectManager->get('MagentoFrameworkAppCacheManager');
$cacheManager->clean('catalog_product_' . $productID);
}
当前,当Cron作业运行时,这是默默失败的。
知道我如何仅清除单个产品ID的缓存?
谢谢 @bxn5。我设法在那里登录了一些错误,并迅速发现cacheManager
的命名空间有些错误。
正确的代码是:
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$cacheManager = $objectManager->get('MagentoFrameworkAppCacheInterface');
$cacheManager->clean('catalog_product_' . $productID);
对于那些与Magento一起运行Varnish的人,也有必要清除那里的数据,而Magento Call似乎并没有完全做到这一点。因此,我添加了卷曲请求以完成特定的清除:
$varnishurl = "www.domainYouWantToPurge.co.uk";
$varnishcommand = "PURGE";
$productID = '760'; // This is the Magento ProductID of the item you want to purge
$curl = curl_init($varnishurl);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $varnishcommand);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['X-Magento-Tags-Pattern: catalog_product_'.$productID]);
$result = curl_exec($curl);
curl_close($curl);
确保您已正确设置了清除配置文件中的清除权限。
如果您查看MagentoInventoryCacheModelFlushCacheByProductIds
,您将看到以下方法(Magento 2.2.3):
/**
* Clean cache for given product ids.
*
* @param array $productIds
* @return void
*/
public function execute(array $productIds)
{
if ($productIds) {
$this->cacheContext->registerEntities($this->productCacheTag, $productIds);
$this->eventManager->dispatch('clean_cache_by_tags', ['object' => $this->cacheContext]);
}
}
在DI的祝福下,我会选择在可能的情况下使用核心代码,而不是使用自己的核心代码。
吻,干燥。
我发现使用此代码的最佳方法
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productR = $objectManager ->create('MagentoCatalogApiProductRepositoryInterface');
$product = $productR->get('product_sku');
$product->cleanCache();
$this->_eventManager->dispatch('clean_cache_by_tags', ['object' => $product]);
请在您的构造函数中初始化对象管理器和productRepository
我现在正在使用这种方式,它正在像魅力一样工作
您可以加载产品对象并致电CleanCache()
首先初始化$ this-> productRepository类似:
public function __construct(
...
MagentoCatalogApiProductRepositoryInterface $productRepository
...
)
{
$this->productRepository = $productRepository;
}
然后在您的代码中调用此:
$product = $this->productRepository->get($sku);
$product->cleanCache();