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.