I want to override a class in a composer installed vendor package on Magento 2.
Firstly I have a child theme of the default theme Luma. Secondly I installed the vendor package via composer.
I have two questions.
- Can I put my code in app/design/frontend/Myvendor/mytheme/<Vendorname_vendormodule>/or do I need to put it inapp/code/
- How can I override this specific class only, which is vendor/<vendorname>/module-<vendormodule>/Block/Product/Info.php?
- 
 I would suggest you override it using custom module in app/codefmsthird– fmsthird2019年03月10日 13:32:34 +00:00Commented Mar 10, 2019 at 13:32
1 Answer 1
For your first question : It depends which code you want to override.
- For example you want to change the theme,the layout and front end display (not any functional change) you can do it. - app/design/frontend/Myvendor/mytheme/<Vendorname_vendormodule>/
- If you want to update/rewrite the logic you have to do it in - app/code/{Vendor}/{Module}.
For your second question : To override block you need to add code in app/code/{Vendor}/{Module} directory by following steps
For example you have to override Magento\Catalog\Block\Product\ListProduct block
1.) create file app/code/{Vendor}/{Module}/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\Block\Product\ListProduct" type="{Vendor}\{Module}\Block\Rewrite\Product\ListProduct" />
</config>
2.) create file app/code/{Vendor}/{Module}/Block/Rewrite/Product/ListProduct.php
<?php
 /**
 * Hello Rewrite Product ListProduct Block
 */
 namespace {Vendor}\{Module}\Block\Rewrite\Product;
 class ListProduct extends \Magento\Catalog\Block\Product\ListProduct
 {
 public function _getProductCollection()
 {
 // Do your stuff here
 }
 }
- 
 Does not work for me sadly. Nothing happens.John– John2019年03月11日 16:41:10 +00:00Commented Mar 11, 2019 at 16:41