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.
[crayon-63e0985c4ab8f826681932/] Using above fucntion Images can be imported directly from...
Override view block using di.xml and add the below code...
You can check a list of called layout XML for...
Follow the below steps to install and set up PWA...
If you want to remove all leading zero's from order,...
Let our Magento expert connect to discuss your requirement.
We offer Magento
certified developers.
Our Magento clientele
is 500+.
We sign NDA for the
security of your projects.
We’ve performed 100+
Magento migration projects.
Free quotation
on your project.
Three months warranty on
code developed by us.