https://embed.notionlytics.com/wt/ZXlKd1lXZGxTV1FpT2lKaU56QmpNemxrTXpJellUWTBOek5sWWpoalpqSmxPRFZtWmpCaFpHVXdZaUlzSW5kdmNtdHpjR0ZqWlZSeVlXTnJaWEpKWkNJNklrbGpiM1pzV2pOcU1VUnBRM1ZUUm1WNFRtdHlJbjA9
When developing a Magento2 app, you may need to change a function in a core class to work in a particular way that is not implemented by default, so it serves your app some purposes.
When you use block, model, controller, helper in Magento 2, it's a bad practice to modify code pulled in a version-controlled package by hand, for some obvious reasons:
vendor
is not (and should not be) controlled, so nobody will get the changes you make.The solution to this problem is to override the files, but...
When you have to modify a core class in Magento2, you have two possibilities:
<aside> ➡️ There are other ways of affecting functionality, such as changing di.xml parameters, Event listeners, but it has its use cases.
</aside>
In this guide, we're taking a look at preference.
A class preference is a method that gives you the ability to modify or rather override a core class implementation.
The way it works is as saying, "Whenever code asks for OriginalClass
, give them MyClass
instead".MyClass
is expected to be a complete implementation of OriginalClass
, plus whatever behavior you add or modify on top.
<aside> ➡️ The class preference method is a powerful way to configure Magento’s core functionality. In some cases, though, it might be too heavy-handed. The disadvantage of using preferences is that can cause conflicts if multiple classes extend the same original class.
To avoid conflicting overrides on the same class, use plugins instead of preferences!
</aside>
If you want to override a core Magento class's implementation, to make it work in a particular way that is not present in the original implementation, then yes. But if you just want to run a function before, around, or after the original function of a class to fulfill a small requirement, then you may consider using plugins instead.
<aside> ➡️ You cannot use plugins on:
<aside> ➡️ When possible, plugins are preferred over class preferences.
</aside>
To create a class preference, we need to create a module.
If not sure, check How to create a module? on how it is done, before proceeding to the next steps of creating overrides.
<aside> ➡️ For the sake of the tutorial, assume that:
Magento\\Catalog\\Model\\Product
getName
Scandiweb
and name MyModule
</aside>Create a class to use as a preference over the original (target) class. Check the following properties:
Scandiweb\\MyModule\\Model\\Product
. Get this value by replacing the Vendor\Module (in our case Magento\\Catalog
) part from the targeted class full name (in our case Magento\\Catalog\\Model\\Product
) with the according to values of a new module (in our case Scandiweb\\MyModule
).