How can we override Magento\Checkout\Model\Cart
class in Magento 2 ?
2 Answers
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" />
</config>
You have to create Cart class in your module in order to extend Magento\Checkout\Model\Cart. E.g:
<?php
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.
-
Great! How about providing a useful answer that includes details as to how to do so rather than just suggesting something without explaining anything? Dec 7, 2022 at 17:00