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,
beforeGetProductmethod will be active. - Next,
aroundGetPrductwill be active. - Finally,
afterGetProductmethod will be active. You can look into thevar/log/debug.logand 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.

