How can we override Magento\Checkout\Model\Cart class in Magento 2 ?


You can override using preference method in di.xml

<?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\Checkout\Model\Cart" type="Vendor\ModuleName\Model\Cart" />

You have to create Cart class in your module in order to extend Magento\Checkout\Model\Cart. E.g:

namespace Vendor\ModuleName\Model;

class Cart extends \Magento\Checkout\Model\Cart
     //override respective methods

If you want to modify some methods on this class, first try to use plugins instead of extending whole class.

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.