Magento 2: How to invalidate indexer programmatically?

How to invalidate indexer programmatically?

Very often we need to perform the indexing. We either run the index manually or we set the index corn-based to run invalidated indexes automatically which we have set to Update on schedule. Some events like Save events automatically re-index a particular index, which we set to update on save.

Well, sometimes we are required to invalidate indexes on certain events programmatically. Let’s see how we can achieve this in this blog.

How to invalidate indexer programmatically?

Let’s assume that we have created a basic module with a suitable Vendor name and module name.

In my case Vendor Name is SbDevBlog and Module name is Indexer.

Let’s create a service class in order to invalidate the indexer programmatically. I am creating an indexerService class inside SbDevBlog\Indexer\Services directory.

I am going to invalidate catalog_category_product index which belongs to Category Products. You may replace it with your index identifier which you need to invalidate.

<?php
/**
 * @copyright Copyright (c) sbdevblog (http://www.sbdevblog.com)
 */

namespace SbDevBlog\Indexer\Services;

use Magento\Framework\Indexer\IndexerInterface;
use Psr\Log\LoggerInterface;

class indexerService
{
    private const CATALOG_CATEGORY_PROD_INDXER = "catalog_category_product";
    /**
     * @var IndexerInterface
     */
    private IndexerInterface $indexer;
    /**
     * @var LoggerInterface
     */
    private LoggerInterface $logger;

    /**
     * Constructor For Service
     *
     * @param IndexerInterface $indexer
     * @param LoggerInterface $logger
     */
    public function __construct(
        IndexerInterface  $indexer,
        LoggerInterface $logger
    )
    {
        $this->indexer = $indexer;
        $this->logger = $logger;
    }

    /**
     * Invalidate Index
     *
     * @return bool
     */
    public function invalidateCategryProductsIndex(): bool
    {
        try {
            $indexer =$this->getIndexerById(self::CATALOG_CATEGORY_PROD_INDXER);
            $indexer->invalidate();
            return true;
        } catch (\InvalidArgumentException $e) {
            $this->logger->error($e->getMessage());
        }
        return false;
    }

    /**
     * Invalidate Indexer By Key
     *
     * @param string $indexerKey
     * @return bool
     */
    public function invalidateIndexById(string $indexerKey): bool
    {
        if (!$indexerKey) {
            return false;
        }
        try {
            $indexer = $this->getIndexerById($indexerKey);
            $indexer->invalidate();
            return true;
        } catch (\InvalidArgumentException $e) {
            $this->logger->error($e->getMessage());
        }
        return false;
    }

 
    /**
     * Get Indexer by id
     *
     * @param string $indexerKey
     * @return IndexerInterface
     */
    private function getIndexerById(string $indexerKey):IndexerInterface
    {
        return $this->indexer->load($indexerKey);
    }
}

That’s it. This will simply invalidate the category products indexer. It is very simple. However, Always handle exceptions. In this case, the Indexer model class can throw InvalidArgumentException on providing invalid identifier; hence I have handled it in try catch block and logged error in order to prevent any kind of issue in website.

Thanks for reading my blog. To re-index programmatically, Visit https://sbdevblog.com/magento-2-how-to-re-index-programmatically/
Use the comment box to give your valuable comments, feedback, and suggestions. Your suggestions are most welcome. Please subscribe and share SbDevBlog.

Download The Source Code

Note: Please verify the code of this blog and the relevant git repository before using it in production.
sb dev blog adobe commece Magento 2

🙂 HAPPY CODING 🙂

4 thoughts on “Magento 2: How to invalidate indexer programmatically?

    1. Thanks for the correction, It was a typo mistake. I have corrected it.

      Regarding IndexerInterface, I have implemented it in this post. thanks, I appreciate your suggestion, keep giving it, it will help me to improve my blog and knowledge. Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *