1

Magento2 has Three ways of extending Feature in native Magento classes and methods

  1. Preference

  2. Plugins

  3. Observer

Which one Use on in which Event ?

1

A broad summary

Try and use plugins where possible. This will have least amount of impact and (hopefully) work well with other extensions. Plugins are super flexible. Best use case is when you want to swap out the value of a entity method for something more dynamic. Plugins take a bit of experimentation to get right.

Plugin for username login

https://github.com/DominicWatts/UsernameLogin/blob/master/Plugin/Magento/Customer/Model/AccountManagement.php

Use observer when a particular event would trigger an action in your extension. For example product save updates external search service with updated attribute values. Observations can be difficult to debug. Use lots of logging.

Last use preference. Complete rewrite of class or method within. Can add new methods. Only rewrite public methods. If your new method requires something not public this will need to be handled. This approach is probably the easiest to follow.

Preference rewrite of contact us post action

https://github.com/DominicWatts/ContactCc/blob/master/Rewrite/Magento/Contact/Controller/Index/Post.php

You can also override classes using composer. But this is outside the scope of your question.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.