Magento 2.1 – Overriding Protected Function in Mini-Cart

magento-2.1mini-cartoverrides

I'm trying to override one protected function in Magento 2, but I am not able to achieve it.
I have edited following files.

di.xml

<preference for="Magento\Checkout\CustomerData\DefaultItem" type="XYZ\Checkout\CustomerData\DefaultItem" />

XYZ\Checkout\CustomerData\DefaultItem

<?php

namespace \XYZ\Checkout\CustomerData;

class DefaultItem extends \Magento\Checkout\CustomerData\DefaultItem
{

    protected function doGetItemData()
    {
        $imageHelper = $this->imageHelper->init($this->getProductForThumbnail(), 'mini_cart_product_thumbnail');
        return [
                'options' => $this->getOptionList(),
                'qty' => $this->item->getQty() * 1,
                'item_id' => $this->item->getId(),
                'configure_url' => $this->getConfigureUrl(),
                'is_visible_in_site_visibility' => $this->item->getProduct()->isVisibleInSiteVisibility(),
                'product_name' => $this->item->getProduct()->getName(),
                'product_sku' => $this->item->getProduct()->getSku(),
                'product_url' => $this->getProductUrl(),
                'product_has_url' => $this->hasProductUrl(),
                'product_price' => $this->checkoutHelper->formatPrice($this->item->getCalculationPrice()),
                'product_price_value' => $this->item->getCalculationPrice(),
                'product_image' => [
                        'src' => $imageHelper->getUrl(),
                        'alt' => $imageHelper->getLabel(),
                        'width' => $imageHelper->getWidth(),
                        'height' => $imageHelper->getHeight(),
                ],
                'canApplyMsrp' => $this->msrpHelper->isShowBeforeOrderConfirm($this->item->getProduct())
                && $this->msrpHelper->isMinimalPriceLessMsrp($this->item->getProduct()),
        ];
    }
}

After clearing caches, when I add product to cart, there is no increment in minicart notification and I'm not able to open minicart and checkout/cart page is coming blank. I have checked in quote_item table and product has been added to the cart. So I think my overriding is not working.

Best Answer

You have keep extra slash in namespace line.

Please remove slash before class namespace in your defaultItem.php file.

Replace

<?php

namespace \XYZ\Checkout\CustomerData;

class DefaultItem extends \Magento\Checkout\CustomerData\DefaultItem
{

With

<?php

namespace XYZ\Checkout\CustomerData;

class DefaultItem extends \Magento\Checkout\CustomerData\DefaultItem
{
Related Topic