Magento2 – Overriding – Module Development Series – – Part5

In this blog post we will see how to override core blocks, models, controllers and customize magento functionality.

Overriding is easily managed in magento using dependency injection. The configuration file to manage this is di.xml located in etc/ folder

Overriding Model

Let’s see how to override Magento/Customer/Model/Customer model

create file Excellence/Hello/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
 	<preference for="Magento\Customer\Model\Customer" type="Excellence\Hello\Model\Rewrite\Customer\Customer" />
</config>

next create Excellence\Hello\Model\Rewrite\Customer\Customer.php file

<?php
    namespace Excellence\Hello\Model\Rewrite\Customer;
 
    class Customer extends \Magento\Customer\Model\Customer
    {
        public function loadByEmail($customerEmail)
        {

            //echo $customerEmail.'<br/>'; exit;
            // Do your stuff here
             return parent::loadByEmail($customerEmail);
        }
 
    }

It’s is important to note that the class we made is of path \Rewrite\Customer\Customer.php This is a practice to follow. When ever overriding class, create a Rewrite folder and make the class path same as class your extending

Overriding Resource Model

Add the following code for resource model

<preference for="Magento\Customer\Model\ResourceModel\Customer" type="Excellence\Hello\Model\Rewrite\Customer\ResourceModel\Customer\Customer" />
<?php
    
    namespace Excellence\Hello\Model\Rewrite\Customer\ResourceModel\Customer;
 
    class Customer extends \Magento\Customer\Model\ResourceModel\Customer
    {
        public function loadByEmail(\Magento\Customer\Model\Customer $customer, $email)
    	{
    		//echo 'resource';exit;
    		parent::loadByEmail($customer,$email);
    	}
 
    }

The way is used to override blocks, controllers as well. In magento1, controller override was a different method from blocks, models but its the same in magento2

Important thing about override in magento is, you should always use parent:: function in it and copy as less code possible from the parent class. e.g you are overriding a function which has 100 lines to code it in it. One way to do it simple copy all the 100 lines to your own class and write your custom do on top of it. Another way is to call parent:: function and copy as little code as possible. The second way is correct way to do it.

  • Anurag Khandelwal

    I think I was wrong above but can you please explain the convention followed to create directory structure as it contradicts to the way you mentioned below model override