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 extendMagento\Checkout\Controller\Cart
.If so, you can do it with an
around
plugin for yourexecute
method in the original controller.Let's take for example
Magento\Checkout\Controller\Cart\Add
controller actionFor this you will need to add this to the
di.xml
of your module:Then create the file
StwBuyXGetY/BuyXGetY/Plugin/Controller/Checkout/Cart/Add.php
with this content:I haven't tested the code, so look out for typos.