Refresh the cache programmatically in Magento 2 at window system
The below code programmatically flushes cache. It worked fine for me.
Case 1: Outside Magento
use Magento\Framework\App\Bootstrap;
include('../app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
try{
$_cacheTypeList = $objectManager->create('Magento\Framework\App\Cache\TypeListInterface');
$_cacheFrontendPool = $objectManager->create('Magento\Framework\App\Cache\Frontend\Pool');
$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();
}
}catch(Exception $e){
echo $msg = 'Error : '.$e->getMessage();die();
}
Case 2: Inside Magento
public function __construct(
Context $context,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
\Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool
) {
parent::__construct($context);
$this->_cacheTypeList = $cacheTypeList;
$this->_cacheFrontendPool = $cacheFrontendPool;
}
$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) {
$this->_cacheTypeList->cleanType($type);
}
foreach ($this->_cacheFrontendPool as $cacheFrontend) {
$cacheFrontend->getBackend()->clean();
}
Hardcoding the types is a bad idea. Instead you can use the same method used by the cache:flush
and cache:clean
commands. The cache manager class can also pull all the cache types for you, as done in the example below.
public function __construct(
\Magento\Framework\App\Cache\Manager $cacheManager
) {
$this->cacheManager = $cacheManager;
}
private function whereYouNeedToCleanCache()
{
$this->cacheManager->flush($this->cacheManager->getAvailableTypes());
// or this
$this->cacheManager->clean($this->cacheManager->getAvailableTypes());
}
@denish,say by using cmd you can clear cache. But ur issue at php command line
In order to run php client as command in window you need to set php as environment available How to set the env variable for PHP?
After that you can run any of magento 2 cli command from cmd like
php bin/magento cache:clean
php bin/magento cache:flush
Or
php bin/magento c:c
php bin/magento c:f
At going at your project location from cmd