7

How to override same class which exist in 2 different custom modules

Eg:

1) I have a file Result.php.

from Vendor\Module1\Block\Result

and almost same Result.php

from Vendor\Module2\Block\Result which overrides

Magento\CatalogSearch\Block\Result

2) Do i have to give

in etc/di of module1

<preference for="Magento\CatalogSearch\Block\Result" type="Vendor\Module1\Block\Result" />

in etc/di of module2

<preference for="Magento\CatalogSearch\Block\Result" type="Vendor\Module2\Block\Result" />

in both the modules1 and 2's ?

3) I have (say) Index.php from controller suppose.

Do the same procedure applies in etc di for both modules?

4) Is there any better approach?

1 Answer 1

1

Plugins is a better approach because you can specify sortOrder on the modifications. Then you can also modify according to your needs, before, after or around the public method you want to modify.

di.xml for module1

<type name="Magento\CatalogSearch\Block\Result">
        <plugin name="module1-result-plugin" type="Vendor\Module1\Plugin\CatalogSearch\Result\ResultPlugin" disabled="false" sortOrder="20"/>
    </type>

di.xml for module2

<type name="Magento\CatalogSearch\Block\Result">
        <plugin name="module2-result-plugin" type="Vendor\Module2\Plugin\CatalogSearch\Result\ResultPlugin" disabled="false" sortOrder="30"/>
    </type>

Here is official documentation for how to use plugins: http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html

Preference should be used for defining public interfaces in your module, example from catalogsearch:

<preference for="Magento\Search\Model\SearchCollectionInterface" type="Magento\CatalogSearch\Model\ResourceModel\Search\Collection" />
1
  • this will not work if you need to add additional methods Commented Aug 8, 2018 at 15:55

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.