The post is all about performing reindexing programmatically in Magento 2.
The way in which Magento transforms the data such as products and categories in order to improve the performance of the frontend is indexing. Whenever there is any change in the data from the backend, i.e., product price updates, a product added under a particular category, etc., the transformed data has to be updated or say reindexed.
This is because the Magento 2 database structure is complicated with multiple database tables that store the prices, users, etc. In order to reflect the changes in the frontend instantly, you need to reindex the data with indexers.
If a developer does not perform Magento 2 reindexing, the changes implemented would take longer to load, possibly annoying the visitor and abandoning your store.
As we do not want this to happen, here’s how to programmatically reindex in Magento 2:
Method to do Reindexing Programmatically In Magento 2:
Create Data.php in app/code/[Vendor]/[Module]/Helper
namespace [Vendor]\[Module]\Helper; use Magento\Framework\App\Helper\AbstractHelper use Magento\Framework\App\Helper\Context; use Magento\Indexer\Model\IndexerFactory; use Magento\Indexer\Model\Indexer\Collection; class Data extends AbstractHelper { private $indexFactory; private $indexCollection; public function __construct( Context $context, IndexerFactory $indexFactory, Collection $indexCollection, ) { parent::__construct($context); $this->indexCollection = $indexCollection; $this->indexFactory = $indexFactory; } public function manuallIndexing() { $indexes = $this->indexCollection->getAllIds(); foreach ($indexes as $index){ $indexFactory = $this->indexFactory->create()->load($index); $indexFactory->reindexAll($index); $indexFactory->reindexRow($index); } } }
Now, you can use this helper class method for indexing.
That’s it.
Feel free to share the solution with fellow developers via social media.
Related Post:
Thank you.