0

I want to override the ProductRepository.php class need to do some changes in the Save function

File Path : vendor/magento/module-catalog/Model/ProductRepository.php

Fucntion Name: Save

How can I Override the ProductRepository.php class which is implement by the \Magento\Catalog\Api\ProductRepositoryInterface class

Our magento2 version is: 2.1.7

2 Answers 2

3

You can either you preference or plugin for this issue.

Use preference:

Step 1: Create a file extending \Magento\Catalog\Model\ProductRepository class in your module:

<?php
namespace YourNamespace\YourModule\Model;

use Magento\Catalog\Model\ResourceModel\Product\Collection;

class ProductRepository extends \Magento\Catalog\Model\ProductRepository
{
 public function save(\Magento\Catalog\Api\Data\ProductInterface $product, $saveOptions = false)
 {
        \\ Your implementation
 }

}

Step 2: paste this line to file di.xml in app/code/YourNamespace/YourModule/etc folder:

<preference for="\Magento\Catalog\Model\ProductRepository" type="YourNamespace\YourModule\Model\ProductRepository"/>

Use plugin:

Step 1: Create plugin class for ProductRepository:

<?php
namespace YourNamespace\YourModule\Plugin;

class ProductRepositoryPlugin
{

   public function aroundSave(
    \Magento\Catalog\Model\ProductRepository $origin,
    $proceed,
    \Magento\Catalog\Api\Data\ProductInterface $product, 
    $saveOptions = false
   )
   {

   }
}

Step 2: Copy these lines to file di.xml in app/code/YourNamespace/YourModule/etc folder:

<type name="\Magento\Catalog\Model\ProductRepository">
    <plugin name="override_class_by_plugin" type="\YourNamespace\YourModule\Plugin\ProductRepositoryPlugin" />
</type>
0

You can use Plugin for change behavior of the class functions by intercepting save() function call and running code before, after, or around that function call.

See the use for source how to use plugin

http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html https://www.mageplaza.com/magento-2-module-development/magento-2-plugin-interceptor.html

First you should create a module which have di.xml at app/code/etc/[Vendorname]/[Module]

di.xml code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Model\ProductRepository">
        <plugin name="change_behavior_of" type="[Vendorname]\[Module]\Plugin\ProductRepositoryPlugin" sortOrder="1" />
    </type>
</config>

Plugin Class

Then plugin class ProductRepositoryPlugin.php is located at app/code/etc/[Vendorname]/[Module]/Plugin

<?php
namespace [Vendorname]\[Module]\Plugin;
class ProductRepositoryPlugin
{

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.