Magento 2 Override Model

A Model represents the data of the application and follow the below steps to override a model.

Create di.xml

File : app/code/PHPCodez/First/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\Catalog\Model\Product" type="PHPCodez\First\Model\Product" />
</config>

Create Product.php

File : app/code/PHPCodez/First/Model/Product.php

<?php
 namespace PHPCodez\First\Model;
 class Product extends \Magento\Catalog\Model\Product {
 public function getName() {
 return $this->_getData(self::NAME)." PHPCodez";
 }
 }

Here I have override the function getName() and append the text ‘PHPCodez’ with the product name

Run the following commands and check and product listing or details page and you can see the text ‘PHPCodez’ appended with product name.

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy
php bin/magento cache:clean

Leave a Reply

Your email address will not be published. Required fields are marked *