cancel
Showing results for 
Search instead for 
Did you mean: 

What is the best approach to override a method completely in Magento2?

What is the best approach to override a method completely in Magento2?

What is the best approach to override a method completely in Magento2?

 

1. Around plugin (before and after plugin can be used to change the argument and return value accordingly)

2. Override a class using di.xml preference for changing a single method.

 

Any other best approaches?

3 REPLIES 3

Re: What is the best approach to override a method completely in Magento2?

Hi @mani_stelli,

 

Best approach suggested by magento and fully future proof is plugin.

 

But in some cases, we are not able to follow plugin approach. In those cases, we do use preference approach. Try for plugin approach first for your requirement.

https://devdocs.magento.com/guides/v2.4/extension-dev-guide/plugins.html

 

Hope this helps you!

Problem Solved! Click Kudos & Accept as Solution!

 

 

Re: What is the best approach to override a method completely in Magento2?

But for plugin, we can change only the input parameter and return value only right? But we can't stop the execution of the original function except using around plugin.

 

But in some discussion, they are saying don't use aroundPlugin.

Re: What is the best approach to override a method completely in Magento2?

Hi @mani_stelli ,

 

Around Plugin are defined such that their code is run both before and after the observed method. This allows you to completely override a method. Around Plugin is used for changing both the arguments and returned values of an original method or add some behavior before and after an original method is called.

 

Performance point of view they mention to avoid using Around plugins.

"Avoid using around method plugins when they are not required because they increase stack traces and affect performance."

https://devdocs.magento.com/guides/v2.4/extension-dev-guide/plugins.html

 

Hope this helps you!

Problem Solved! Click Kudos & Accept as Solution!