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" />

\code \StwBuyXGetY \BuyXGetY \Controller\Checkout\Cart.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.)


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" />

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.

|improve this answer|||||
  • Hi @Marius, I edited my question, could you please check it??? – Keerthana Aug 17 '16 at 6:06
  • @Keerthana. You edited the question adding an unrelated question to it. Please keep them separate. If you have an additional question please ask an it here – Marius Aug 17 '16 at 6:10
  • 1
    I have posted another question magento.stackexchange.com/questions/131716/… and edited this one. Please check. – Keerthana Aug 17 '16 at 6:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.