We sacrifice by not doing any other technology, so that you get the best of Magento.

We sacrifice by not doing any other technology, so that you get the best of Magento.

    In this article, I will guide you on how to use a plugin to block Override in Magento 2.

    Add di.xml file in app/code/Magemonkeys/HelloWorld/etc/ and copy the following code in it:

    <?xml version="1.0"?>
     
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <type name="MagentoCatalogBlockProductView">
            <plugin name="magemonkeys-helloworld-product-block" type="MagemonkeysHelloWorldPluginProductPlugin" sortOrder="5" />
        </type>
    </config>

     

    Here enable all the methods containing before, after, and around methods.

    • Firstly, beforeGetProduct method will be active.
    • Next, aroundGetPrduct will be active.
    • Finally, afterGetProduct method will be active. You can look into the var/log/debug.log and confirm the method execution sequence.

    Add ProductPlugin.php file in app/code/Magemonkeys/HelloWorld/Plugin/ and copy the following code in it:

    <?php
     
    namespace MagemonkeysHelloWorldPlugin;
     
    class ProductPlugin
    {    
        public function beforeGetProduct(MagentoCatalogBlockProductView $subject)
        {
            // logging to test override    
            $logger = MagentoFrameworkAppObjectManager::getInstance()->get('PsrLogLoggerInterface');
            $logger->debug(__METHOD__ . ' - ' . __LINE__);        
        }
        
        public function afterGetProduct(MagentoCatalogBlockProductView $subject, $result)
        {
            // logging to test override    
            $logger = MagentoFrameworkAppObjectManager::getInstance()->get('PsrLogLoggerInterface');
            $logger->debug(__METHOD__ . ' - ' . __LINE__);
            
            return $result;
        }
        
        public function aroundGetProduct(MagentoCatalogBlockProductView $subject, Closure $proceed)
        {
            // logging to test override    
            $logger = MagentoFrameworkAppObjectManager::getInstance()->get('PsrLogLoggerInterface');
            $logger->debug(__METHOD__ . ' - ' . __LINE__);
            
            // call the core observed function
            $returnValue = $proceed(); 
            
            // logging to test override        
            $logger->debug(__METHOD__ . ' - ' . __LINE__);
            
            return $returnValue;
        }    
    }
    ?>
    

     

    Hope this guide helped you to understand the process to block override using plugin. If you have any queries regarding the blog, please comment below. We will assist you as soon as possible.

    field_5bfb909c5ccae

      Get a Free Quote