如何清除 Magento 2 中单个 product_id 的缓存

Bio*_*maj 1 php caching magento2

我编写了一个 cron 作业,它检查直接在数据库中进行的库存数量更改,因此绕过了 Magento 核心,该核心可以处理缓存过期。

我希望能够通过以下方式使用对象管理器:

public function clearCacheforProduct($productID) {
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $cacheManager = $objectManager->get('\Magento\Framework\App\Cache\Manager');
    $cacheManager->clean('catalog_product_' . $productID);
}
Run Code Online (Sandbox Code Playgroud)

当前,当 cron 作业运行时,这会以静默方式失败。

知道如何清除单个产品 ID 的缓存吗?

Bio*_*maj 5

谢谢@bxN5。我设法在那里记录了一些错误,并很快发现 的命名空间cacheManager有点错误。

正确的代码是:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$cacheManager = $objectManager->get('\Magento\Framework\App\CacheInterface');
$cacheManager->clean('catalog_product_' . $productID);
Run Code Online (Sandbox Code Playgroud)

对于那些使用 Magento 运行 Varnish 的人来说,也有必要清除那里的数据,而 Magento 调用似乎并没有完全完成。所以我添加了一个 cURL 请求来完成特定的清除:

$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);
Run Code Online (Sandbox Code Playgroud)

确保在 Varnish 配置文件中正确设置了清除权限。