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:
1 2 3 4 5 6 7 |
<?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="Magento\Catalog\Block\Product\View"> <plugin name="magemonkeys-helloworld-product-block" type="Magemonkeys\HelloWorld\Plugin\ProductPlugin" sortOrder="5" /> </type> </config> |
Here enable all the methods containing before, after, and around methods.
beforeGetProduct
method will be active.aroundGetPrduct
will be active.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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?php namespace Magemonkeys\HelloWorld\Plugin; class ProductPlugin { public function beforeGetProduct(\Magento\Catalog\Block\Product\View $subject) { // logging to test override $logger = \Magento\Framework\App\ObjectManager::getInstance()->get('\Psr\Log\LoggerInterface'); $logger->debug(__METHOD__ . ' - ' . __LINE__); } public function afterGetProduct(\Magento\Catalog\Block\Product\View $subject, $result) { // logging to test override $logger = \Magento\Framework\App\ObjectManager::getInstance()->get('\Psr\Log\LoggerInterface'); $logger->debug(__METHOD__ . ' - ' . __LINE__); return $result; } public function aroundGetProduct(\Magento\Catalog\Block\Product\View $subject, \Closure $proceed) { // logging to test override $logger = \Magento\Framework\App\ObjectManager::getInstance()->get('\Psr\Log\LoggerInterface'); $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.
If you want get query string params in controller file,...
Create di.xml and add the below code Magemonkey/Redirect/etc/frontend/di.xml [crayon-62845f1e6ad7c618159267/] Create...
You can try below code to change local date to...
Step 1: First you need to add registration.php file in...
Step1 : Override message.js in current theme file on the...