Magento 2 has made a breakthrough by implementing Object Manager system. This systems enables developers to write plugins – the replacement for Magento1’s class rewrites – that can change or extend the behavior of any public methods in Magento class. We will get right into it in a moment.

Declare a plugin

Add the following configuration to your di.xml file.

  • _ObservedType: the path to the class that the plugin observes
  • _pluginName: an arbitrary name that identify the plugin
  • _pluginClassName: The path to the class that execute the plugin

Now we need to create plugin file. I suggest putting the file in your Model/Plugin folder. After that, choose an appropriate method to implement your plugin.

Before method

This method is used to change the arguments or add some behavior before the original method is called. You just have to prefix the name of the original method with “before”. For example:
class Plugin

The first parameter $subject is the object that our method was called on. The next parameters are the exact copy of the original method parameters. These parameters will let you change the values of the arguments before passing them to he real method

After method

This method is used to change the values returned by an original method or add some behavior after the original method is called.

For example:

class Plugin

Similar to the before method, $subject is the object that our method was called on. The second parameter is the result of the original method.

Around method

This method is called during the execution of the original method, or this is the replacement of it. Here I will point out an actual example in one of our extension: Appointment Booking

Use Magento\Backend\Block\Widget\Form;

In the above example, $subject will point to the original class as the Form class. $procede is of type \Closure, which is actually an anonymous function. The third argument is $form, which is the only parameter of the original method. By calling $procede($form), we actually calling the original method.
The plugin then check the data from the form and add Custom attribute to the form: enctype as multipart/form-data. This is a nice way to add enctype attribute to Magento’s original form and allow user to upload images