Magento 2 – How to Override getSectionData() Method in CustomerData/Cart.php

magento2mini-cartmoduleoverridesplugin

Is it possible to overwrite "public function getSectionData()" of class magento-checkout/CustomerData/Cart.php only with the help of Plugin

My 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">
<!--    <type name="Magento\Checkout\CustomerData\AbstractItem">
    <plugin name="AddAttPlug" type="Trimantra\ShippingMessage\Plugin\DefaultItem" disabled="false" sortOrder="10"/>
    </type>-->
    <type name="Magento\Checkout\CustomerData\Cart">
    <plugin name="AddMsgPlug" type="Trimantra\ShippingMessage\Plugin\Cart" disabled="false" sortOrder="10"/>
    </type>
</config>

My class file

    <?php

namespace Trimantra\ShippingMessage\Plugin;

class Cart 
{
    public function afterGetSectionData(\Magento\Checkout\CustomerData $subject, $result)
    {

    ......
    return  $result;

    }
}

Best Answer

You can declare the following in your module etc/di.xml :

<config>
    <type name="Magento\Checkout\CustomerData\Cart">
        <plugin name="my-custom-plugin" type="Vendor\Module\Plugin\CustomerData" sortOrder="1"/>
    </type>
</config>

Then in your Vendor\Module\Plugin\CustomerData.php you can write:

<?php

namespace Vendor\Module\Plugin;

class CustomerData {

    public method afterGetSectionData(\Magento\Checkout\CustomerData\Cart $subject, $result)
    {
        // Get the previous data
        $data = $result;
        // Append variable
        $data .= "test";
        return $data;
    }
}

NB: you can also write an aroundGetSectionData and a beforeGetSectionData based on your needs.