How to override model in Magento 2?

by aniya.jaskolski , in category: PHP CMS , 8 months ago

How to override model in Magento 2?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 3 months ago

@aniya.jaskolski 

To override a model in Magento 2, you will need to create a custom module and use a preference to specify your custom model class in the di.xml file.


Here's an example of how to do this:

  1. First, create a custom module by creating the following directory structure in your Magento installation: app/code/YourCompany/YourModule.
  2. Create a registration.php file in the module root directory with the following code:
1
2
3
4
5
6
<?php
MagentoFrameworkComponentComponentRegistrar::register(
    MagentoFrameworkComponentComponentRegistrar::MODULE,
    'YourCompany_YourModule',
    __DIR__
);


  1. Create a module.xml file in the etc directory with the following code:
1
2
3
4
5
6
7
8
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="YourCompany_YourModule" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>


  1. Create a di.xml file in the etc directory with the following code:
1
2
3
4
<?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="MagentoCatalogModelProduct" type="YourCompanyYourModuleModelProduct" />
</config>


  1. Create a Product.php file in the Model directory with the following code:
1
2
3
4
5
6
7
<?php
namespace YourCompanyYourModuleModel;

class Product extends MagentoCatalogModelProduct
{
    // your custom code goes here
}


This will override the MagentoCatalogModelProduct model with your custom model class. You can now add your custom code to the Product class and it will be used instead of the original model class.


Remember to run the following commands to enable the module and clear the cache:

1
2
3
php bin/magento module:enable YourCompany_YourModule
php bin/magento setup:upgrade
php bin/magento cache:clean