How to override a Model in Magento 2 - Paul Meștereagă
Magento 2

How to override a Model in Magento 2

In this short tutorial I will show you how to override a Model in Magento 2 and also an alternative to rewriting introduced in Magento 2.

author

Paul Mestereaga

January 16, 2020

In this short tutorial I will show you how to override a Model in Magento 2 and also an alternative to rewriting introduced in Magento 2.

I assume you already have a new module created where you will write your customizations. If not here is a tutorial on how to create a new module in Magento 2.

Write a preferrence

For this tutorial let’s rewrite the Quote model found here Magento\Quote\Model\Quote.

In your custom module create the file <Vendor>/<Module>/etc/di.xml if you don’t have it already.

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
   <preference for="Magento\Quote\Model\Quote" type="Vendor\Module\Model\Quote"/>
</config>

Here we defined a preference, for attribute it’s the class we want to rewrite and type attribute represents the new class we create.

Extend the Model

Now let create our new class that extends Magento\Quote\Model\Quote.

Create the file <Vendor>/<Module>/Model/Quote.php

<?php 
namespace Vendor\Module\Model;
 
class Quote extends \Magento\Quote\Model\Quote
{
 
//write your customizations here
 
}

That’s how simple it is to override a Model in Magento 2. Let’s look at the alternative.

An alternative to not override a model in Magento 2

The alternative to rewriting it is by using plugins. Please check the documentation here on how to use and create plugins. They are something introduced in version 2 of Magento.

You can check all my Magento 2 tutorials here.

Magento 2 from Zero to Beginner Free Online Course

In 10 hours you will have all the basic knowledge so that you could develop your modules without wandering around how to implement stuff.

Related Posts

Magento checkout optimization

15 Dec 2022

|

Paul Mestereaga

Optimizing the checkout process on your Magento eCommerce website is essential for increasing conversions and improving customer satisfaction. A seamless checkout experience can make all the difference in the success of your online store.

3 Things That Kill Your Magento Store’s Conversion Rate

10 Dec 2021

|

Paul Mestereaga

The store receives a lot of traffic, and you market to the right audience. The brand is actively promoted on social media and succeeds in SEO, so the marketing efforts appear to be working.
But what if it doesn’t lead to many sales?

optimize-magento-preview

FREE!

Magento 2
Optimization guide

Wondered how you can make your Magento load faster? Wonder no more. Here is a step by step guide that helps you.