Magento 2 Override Classes Using Plugin

There are three methods to override classes using the plugin:

  • Before Method
  • After Method 
  • Around Method

Before Method

Before running the plugin priorly to an observed method, if the method is not being modified, the same argument number must be returned in an array that the method accepts or nullifies. The method which is being extended need to have an identical name with a prefix before.

<?php
namespace VendorName\ModuleName\Plugin\Model;
 
class Product
{
    public function beforeSetPrice(\Magento\Catalog\Model\Product $subject, $price)
    {
        $price += 10;
        return [$price];
    }
}

After method

Once the original method has been called, after methods would be executed. Besides a class object, the method accepts another argument and that also the result that must be returned. The method which is being extended has to have a similar name with prefix after.

<?php
namespace VendorName\ModuleName\Plugin\Model;
 
class Product
{
    public function afterGetName(\Magento\Catalog\Model\Product $subject, $result)
    {
        $result .= ' (Welcome)';
        return $result;
    }
}

Around method

With the around method, the original method will be wrapped. Also, this method allows code execution both before and after the original method. It accepts another argument receives is callable which enables other plugins to call in the chain. The method that is being extended has to have a similar name with prefix around.

<?php
namespace VendorName\ModuleName\Plugin\Model;
 
class Product
{
    public function aroundSave(\Magento\Catalog\Model\Product $subject, \callable $proceed)
    {
        // before save
        $result = $proceed();
        // after save
 
        return $result;
    }
}

If you need any kind of help you can visit TheOnlineHelper