Site icon MageComp Blog

How to Override core code using Custom Plugin in Magento 2

How to Override core code using Custom Plugin in Magento 2

When it comes to fulfill digital needs and give the personalized touch, it always ends up with customization. To customize default Magento store functionality, you need to make changes in default Magento core function files. But, we have never recommended modifying default Magento core files, but an alternative way is to override core files which is a safe and easy way to achieve customization. Compared to Magento 1, overriding and manipulating with classes is becoming much easier for a developer in Magento 2. Also, it allows us more ways of extending the native functionalities.

By default, there are three different ways to override core functionalities.
1. Using preference
2. Using event\observer
3. Using a plugin

Among this, we suggest you use the plugin method to rewrite all files in a convenient way. Picking up plugin from a list is a clever choice because it helps us to reduce conflicts. The plugin offers you an extensive functionality to execute your custom code before, after or sequentially with the specified function or event.

Basically, there are three different types of plugins :
1. Before Method
2. After Method and
3. Around

As the name suggests these plugins methods allows us to execute our custom logical code before, after or around our observing methods. Let’s take a deep dive and understand how to implement different types plugins.
Just like Preferences, plugins are also declared in etc\di.xml file available at below path.
app\code\Vendor\Extension\etc\frontend\di.xml


    
        
    

Once, you have declared your plugin, you can proceed with implementing these plugins methods. For better understanding, here we have used these three different methods with the cart before, after and around actions.
You just need to create ‘Plugincart.php’ file at below location and add your method code and logic.
app\code\Vendor\Extension\Model\Plugincart.php

1) Before
In before method, the first argument will be always class object and rest will be Original Function Argument.

When you are using after method, your first argument will be always class object and Second will be Result, so you can easily modify the result.
The last method is around and when you are using around method, your first argument will be the class object and rest will be callable that allows you to call original function with arguments.
Comment down below if you are looking for any help regarding this code.
Happy Coding!
Exit mobile version