Magento 2 : Override Block , Controller In Magento2

Sometimes you need to change the core functionality of Magento but it is not a good idea to change the core functionality of Magento 2. For this Magento provide a way to override Magento Block, Controller, And Model for writing your logic.

Let’s see how to override Magento core file inside your module.

Override Block In Magento

Here we are going to override Magento (vendor/magento/module-catalog/Block/Product/View.php)  

First of all create di.xml file in your etc folder (Vendor_Name/Module_Name/etc) and write this code

<?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_Name\Module_Name\Block\Rewrite\Product\View" /> 
</config>

Now create View.php file inside the folder (Vendor_Name/Module_Name/Block/Rewrite/Product).

<code><?php namespace Vendor_Name\Module_Name\Block\Rewrite\Product;  
class ListProduct extends \Magento\Catalog\Block\Product\ListProduct 
 { 
protected function _prepareLayout()  
{ 
// add your own login here ......
 } 
}

Overriding Controller In Magento

Here we are going to override Magento (vendor/magento/module-catalog/Controller/Product/View.php) 

First of all di.xml file in your etc folder (Vendor_Name/Module_Name/etc) and write this code.

<?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\Controller\Product\View" type="Vendor_Name\Module_Name\Controller\Rewrite\Product\View" />
</config>

Now Create View.php in folder (Vendor_Name/Module_Name/Controller/Rewrite/Product)

<?php
namespace Vendor_Name/Module_Name/Controller/Rewrite/Product
class View extends Magento/Catalog/Controller/Product/View
{
// Add your adction and logic here.....
}
?>