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.

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.

Sign up for the newsletter

Stay up to date with the latest eCommerce related news.
Be the first to hear when new resources and articles are posted on the website.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Related Posts

Is Magento 2 slow on localhost?

20 Feb 2020

|

Paul Mestereaga

A fresh install of Magento 2 slow on localhost? Here are some steps you can take to make your Magento 2 faster on your localhost.

Extend Magento 2 jQuery Widget

18 Jun 2019

|

Paul Mestereaga

In this short tutorial we will learn how to extend Magento 2 jQuery widget with our custom logic.

Optimize Magento 2

Free guide to help you optimise your Magento 2 installation and improve your website speed

Get your free optimisation guide.

Enter your name and email to join my mailing list in exchange for the free download. You can opt out any time.


Can I email you?

I will use the information you provide on this form to stay in touch, send you updates, and send marketing emails about our products and services. You can unsubscribe at any time through a link in the footer of an email from me. For more information, please read the Privacy Policy.