There are two step to override Block, Model And Controller file
1) Add preference in di.xml
2) Create block, model and controller file in your module
Namespace: Prince
Module Name: Helloworld
For example to override catalog product ListProduct block
1) Create di.xml file in Folder Prince/Helloworld/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="Prince\Helloworld\Model\Rewrite\Catalog\Product" />
</config>
2) Create ListProduct.php in Folder Prince/Helloworld/Block/Rewrite/Product
<?php
namespace Prince\Helloworld\Block\Rewrite\Product;
class ListProduct extends \Magento\Catalog\Block\Product\ListProduct
{
public function _getProductCollection()
{
// Do your code here
}
}
For example to override catalog product model.
1) Add preference in di.xml at Prince/Helloworld/etc
<preference for="Magento\Catalog\Model\Product" type="Prince\Helloworld\Model\Rewrite\Catalog\Product" />
2) Create Product.php Model file in Folder Prince/Helloworld/Model/Rewrite/Catalog
<?php
namespace Prince\Helloworld\Model\Rewrite\Catalog;
class Product extends \Magento\Catalog\Model\Product
{
public function isSalable()
{
// Do your code here
return parent::isSalable();
}
}
Overriding Controller
1) Add preference in di.xml at Prince/Helloworld/etc
<preference for="Magento\Catalog\Controller\Product\View" type="Prince\Helloworld\Controller\Rewrite\Product\View" />
2) Create View.php in Folder Prince/Helloworld/Controller/Rewrite/Product
class View extends \Magento\Catalog\Controller\Product\View
{
public function execute()
{
// Do your stuff here
return parent::execute();
}
}
You can override other block,model and controllers using same approach.