<aside> ➡️ The pages under the Engineering page are currently curated by the company's chief technical officer (CTO). To contribute, please leave a comment. How to comment?

</aside>

https://embed.notionlytics.com/wt/ZXlKd1lXZGxTV1FpT2lJeVlXRTBZbVZtTURjNU9HVTBNMlUyT1dVMVlUUTFNek5sTlRabU9UazJNeUlzSW5kdmNtdHpjR0ZqWlZSeVlXTnJaWEpKWkNJNklrbGpiM1pzV2pOcU1VUnBRM1ZUUm1WNFRtdHlJbjA9

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 plugins.

What is a plugin?

Magento 2 Plugin is referred to as a class extension that allows modifying the behavior of a public class or method by intercepting a function call and running code either before or after or around the function call. The plugin allows you to substitute or extend the behavior of original, public methods for any class or interface.

Why and when should I use plugins?

If you need to:

<aside> ➡️ Plugins can not be used on the __construct method of a class.

</aside>

What type of plugin should I use?

There are three types of plugins namely:

How to create a plugin?

We will be creating a plugin for the below class example: