Ability of Plugins in Magento 2

Here is list of Ability of Plugins in Magento 2.

  • There are three types of plugins: around, before and after.
  • Plugins only work on public methods.
  • Plugins do not work on final methods, final classes.
  • Plugins can be used on interfaces, abstract classes or parent classes.
  • Plugins are mostly used for solution of Module/Class override confliction.

– Before plugins modify the input arguments to a method. You can change them to any value.
Example from: \Magento\Catalog\Block\Product\ListProduct

To modify the the argument of prepareSortableFieldsByCategory($category) method, add a method to the plugin class:
For this we need to define methode name just with prefix “before”.
The method above is run before “\Magento\Catalog\Block\Product\ ListProduct::prepareSortableFieldsByCategory”.
The return value for the before plugin determines the arguments going into the next plugin or the final targeted method.

– After plugins are used to modify the return value.
Example from: \Magento\Catalog\Block\Product\ListProduct

If you need to modify the output from a public method, use an after plugin.
In our example class, let’s modify the getProductPrice($product). As such in our plugin class, we would create:

The after plugin includes the input parameters in addition to the return result.

– The around plugin modification the input and output of a function. The original function is passed in as a callback and, by standard, is named “$proceed”.
Example from: \Magento\Catalog\Block\Product\ListProduct

In our example class, let’s modify the getProductPrice($product). As such in our plugin class, we would create:

For this we need to define methode name just with prefix “around”.
We should return the “Original methods returned value” for execute next plugin…
*In case the callable is not declared, the calling to neither the next plugin nor the original method is achieved.

How plugins work

When you create a plugin entry, Magento automatically generates a class wrapper for the plugin target.
For example, if you want to modify “\Magento\Catalog\Model\Product” , Magento will auto-generate the \Magento\Catalog\Model\Product\Interceptor class.

Every function, that you want to modify, inside the target class will be represented in the auto-generated interceptor class.
if you add new functions to a target class, you may need to delete the auto-generated interceptor class from the “/generated” folder.

Q. How do multiple plugins interact, and how can their execution order be controlled?
– When a plugin is declared in “di.xml”, the “sortOrder” attribute can be set. The lower the sort order will be executed prior in the list.

Q. In which cases should plugins be avoided?

– Plugins are useful to modify the input, output of “an existing method”. So it is best to be avaoided in situations where “the flow of data does not have to be modified”.
So use Event/Observer when don’t want to change flow of Data…