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:

  1. Modifying core files may have a certain influence on another program or module.
  2. Your modifications will be wiped out when you update the framework, those classes you modified will be replaced with new core files.
  3. Code in 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...

How to Modify files without touching the source code?

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.

What is a class 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>

Should I use a class preference?

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>

How to preference a class?

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:

1. Create an override class

Create a class to use as a preference over the original (target) class. Check the following properties: