Magento 2, PHP

Magento 2: Overriding Model

How do I block spammer and scanners?

In a typical Model-View-Controller-based application, models are used to connect to the database and process data from and to it. Magento has adapted this pattern slightly.

Resource Models are objects that contain code that fetches data from a data store. In practice, this means a resource model is the object that contains the SQL building and fetching code, as well as references to objects that connect to the main Magento database.

Models are objects that contain database-agnostic code for interacting with a type of data. In traditional data modeling terms, your model objects contain the business logic for a particular type of object (types include Product and Customer).

A Magento model object contains a reference to a resource model, which it uses to load its data. There’s an individual resource model object for each model object. For example, a Product Model has a Product resource model.

In some case for custom requirement we need to change logic of Model to do that we can take following example.

Lets override catalog product model.

Step 1 – First of all create di.xml file in Folder Done/Hello/etc

<?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="Done\Hello\Model\Rewrite\Catalog\Product" />
</config>

Step 2 – Now create Product.php Model file in Folder Done/Hello/Model/Rewrite/Catalog

<?php
namespace Done\Hello\Model\Rewrite\Catalog;
class Product extends \Magento\Catalog\Model\Product
{
public function isSalable()
{
// Do your stuff here
return parent::isSalable();
}
}
Tags :