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.

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.

Is your Magento slow?

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

Related Posts

How to create a product attribute using Data Patches in Magento 2.3

26 Mar 2020

|

Paul Mestereaga

This is a short tutorial in which we will learn to create a product attribute using Data Patches in Magento 2.3

Declarative schema in Magento 2.3+

16 Mar 2020

|

Paul Mestereaga

In this tutorial we will learn the how to configure a declarative schema in Magento 2.3, perform database operations using declarative schema, create a schema whitelist and create data and schema patches.

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.