Magento 2 : Need to perform clean cache programmatically after records save
Pregunta
In admin side, I want to clean "eav" cache type on records save. I added code in afterSave() function and function also call after save records. But, I think it's not working because, parent afterSave() action perform after my function execute.
My code :
app/code/VendorName/ModuleName/Model/ResourceModel/MyFile.php
/**
* Action perform after save/duplicate records
*
* @param \Magento\Framework\DataObject $customer
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function _afterSave(\Magento\Framework\DataObject $object) {
$this->cacheManager->clean(['eav']);
return parent::_afterSave($object);
}
Note : After save records if I execute php bin/magento c:c eav
Then, I received perfect output.
How can I solve this point?
Anyhelp would be appriciated.
Thanks.
Solución
Can you try this,
<?php
protected $cacheTypeList;
protected $cacheFrontendPool;
public function __construct(
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
\Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool
) {
$this->cacheTypeList = $cacheTypeList;
$this->cacheFrontendPool = $cacheFrontendPool;
}
public function flushCache()
{
$_types = array_keys($this->cacheTypeList->getTypes()); //For all cache clean.
foreach ($_types as $type) {
$this->cacheTypeList->cleanType($type);
}
foreach ($this->cacheFrontendPool as $cacheFrontend) {
$cacheFrontend->getBackend()->clean();
}
}
UPDATE :
For single cache clean :
$this->cacheTypeList->cleanType('eav'); // write cache tag name
foreach ($this->cacheFrontendPool as $cacheFrontend) {
$cacheFrontend->getBackend()->clean();
}
Otros consejos
Try this code
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cacheTypeList = $objectManager->get(\Magento\Framework\App\Cache\TypeListInterface::class);
$cacheFrontendPool = $objectManager->get(\Magento\Framework\App\Cache\Frontend\Pool::class);
$types = array(
'config',
'layout',
'block_html',
'collections',
'reflection',
'db_ddl',
'eav',
'config_integration',
'config_integration_api',
'full_page',
'translate',
'config_webservice'
);
foreach ($types as $type) {
$cacheTypeList->cleanType($type);
}
foreach ($cacheFrontendPool as $cacheFrontend) {
$cacheFrontend->getBackend()->clean();
}
Hope It helps
Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange