Overriding Block, Model, Controller, Helper in Magento 2

Magento 2: Overriding Block, Model, Controller, Helper using Preference


You can create a skeleton of module from Module Generator.
After creating a module structure update your module to database using command line code :

To every magento project there needs certain level of customization on overriding magento core classes. Editing and adding our custom code on magento core classes is a bad practice since they all will be overwritten during magento upgrade. So, there comes a concept of magento classes override. For this magento 2 has two approaches, they are :

1. Using preference
2. Using plugins

Today I will be discussing on using preference for overriding core customer module.

OVERRIDING CUSTOMER BLOCK

Step #1 – Create a di.xml file in a folder Sagar/ClassOverride/etc

Step #2 – The next step to override Magento2 Block is to create a Register.php Block file in the folder Sagar/ClassOverride/Block/Form

OVERRIDING CUSTOMER MODEL

Step #1 – Create a di.xml file in a folder Sagar/ClassOverride/etc

Step #2 – The next step to override Magento2 Model is to create a Customer.php Model file in the folder Sagar/ClassOverride/Model

OVERRIDING CUSTOMER CONTROLLER

Step #1 – Create a di.xml file in a folder Sagar/ClassOverride/etc

Step #2 – The next step to override Magento2 Controller is to create a CreatePost.php Controller file in the folder Sagar/ClassOverride/Controller/Account

OVERRIDING CUSTOMER HELPER

Step #1 – Create a di.xml file in a folder Sagar/ClassOverride/etc

Step #2 – The next step to override Magento2 Helper is to create a Address.php Helper file in the folder Sagar/ClassOverride/Helper

You can override classes of other modules using similar approach.

You can find complete code at : Github

Note : The preferences in di.xml are commented. Please uncomment them to use to your own.

More blogs on overriding classes in magento 2 are Mukesh Chapagain Blog & Inchoo