Magento 2: Override a Method Using Plugin

Plugins

A plugin, or interceptor, is a class that modifies the behaviour of public class functions by intercepting a function call and running code before, after, or around that function call. This allows you to substitute or extend the behaviour of original, public methods for any class or interface.

Extensions that wish to intercept and change the behaviour of a public method can create a Plugin class.In the previous blog, we changed the product name by using Preference, Now we will try to do this in another way, using Plugin.

For declaring a plugin we will create a di.xml file and paste the following code into it.

<type name="Magento\Catalog\Model\Product">
   <plugin name="Gm_Module::PluginName" type="Gm\Module\Plugin\Catalog\Model\ProductPlugin" sortOrder="1" />
</type>

In the code above the “name” attribute in <type> element must map with the path of the target class. 

In the <plugin> element, the “name” attribute contains: VendorName_ModuleName::PluginName you can add your module name here and the name of the plugin to it in my example I have named it as Gm_Module::renameProduct. After that we will put the path of the class that overrides the target class in the “type” attribute.sortOrder is used to assign sorting in which the other plugins will execute in order.

Next, we will create a ProductPlugin.php file in Gm\Module\Plugin\Catalog\Model and add the following codes:

<?php
namespace Gm\Module\Plugin\Catalog\Model;
use Magento\Catalog\Model\Product;
class ProductPlugin
{

  public function afterGetName(Product $subject, $result)
      {
         return $result. ' Gm After Plugin';
       }

}

Here We are using the After listener Plugin.

There is a rule to set the method name, which you should follow if you want your plugin to work correctly:  add a prefix before|around|after to the method name and set the first letter of the target method to capital. E.g: afterGetName().

In afterGetName() method, the $subject parameter plays a role as $this of the core class. It means you can get the public method or variable of the core class. And after the core method is executed, Magento 2 passes the result and arguments to the next after method that follows. It is the reason why the $result is passed in the afterGetName() method.
Once you write this code then clean the cache and see your result.

Limitations:


Plugins can not be used on the following:

  • Final methods
  • Final classes
  • Non-public methods
  • Class methods (such as static methods)
  • __construct and __destruct
  • Virtual types
  • Objects that are instantiated before Magento\Framework\Interception are bootstrapped
  • Objects that implement Magento\Framework\ObjectManager\NoninterceptableInterface

Leave a Comment

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