Magento – How to override cartcontroller in magento 2

cartcontrollersmagento2overrides

I want to override cartcontroller(checkout/controller/cart.php) by my module controller. Can anyone help me please? Any help will be appreciated.

I just tried, But it is not working. My files are,

\code \StwBuyXGetY \BuyXGetY \etc\di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <preference for="Magento\Checkout\Controller\Cart"
             type="StwBuyXGetY\BuyXGetY\Controller\Checkout\Cart" />
</config>

\code \StwBuyXGetY \BuyXGetY \Controller\Checkout\Cart.php

<?php
namespace StwBuyXGetY\BuyXGetY\Controller\Checkout;
class Cart extends \Magento\Checkout\Controller\Cart
{
    public function execute(){
        echo 'Hello World'; exit;}
}

Please help. (Note:- I just put the dummy content in cart.php, this is not the actual function.)

Best Answer

First of all...I advice against rewriting controllers.
Actually I advice against rewriting anything if you can do it an other way.
Second: The class Magento\Checkout\Controller\Cart is an abstract class. It is never instantiated so you cannot rewrite it.
I assume you want to replace the behavior of the execute method from one of the classes that extend Magento\Checkout\Controller\Cart.
If so, you can do it with an around plugin for your execute method in the original controller.
Let's take for example Magento\Checkout\Controller\Cart\Add controller action

For this you will need to add this to the di.xml of your module:

 <type name="Magento\Checkout\Controller\Cart\Add">
    <plugin name="buy-x-get-y" type="StwBuyXGetY\BuyXGetY\Plugin\Controller\Checkout\Cart\Add" sortOrder="1" />
</type>

Then create the file StwBuyXGetY/BuyXGetY/Plugin/Controller/Checkout/Cart/Add.php with this content:

namespace StwBuyXGetY\BuyXGetY\Plugin\Controller\Checkout\Cart;
class Add
{
    public function aroundExecute(\Magento\Checkout\Controller\Cart\Add $add, \callable $proceed)
    {
        //your code goes here
        //if you don't want the original method to be called ignore what'e below.
        $returnValue = $proceed();
        return $returnValue;
    }
}

I haven't tested the code, so look out for typos.