Magento – How to override private function in Model (Magento-2)

magento-2.1.7PHP

My di.xml file

<?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\Customer\Model\ResourceModel\AddressRepository" type="Maha\CreateLastname\Model\ResourceModel\AddressRepository" />
</config>

AddressRepository.php file(override model file)

<?php
    namespace Maha\CreateLastname\Model\ResourceModel; 
    class AddressRepository extends \Magento\Customer\Model\ResourceModel\AddressRepository
    { 
        private function _validate(CustomerAddressModel $customerAddressModel)  {
            echo "Model Rewrite Working";
            die();
        }
    }

I want override the private function in this code. What can I do? I want to change anything in my code

Best Answer

Private functions cannot overridden in child class.

If you want to change the logic in _validate function you can use below method.

Override save function, inside that instead of calling $this->_validate($addressModel) function use your own custom function, like below

private function _validateCustom(CustomerAddressModel $customerAddressModel) {
//your custom validation logic
}

Change the di.xml into

<?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\Customer\Api\AddressRepositoryInterface" type="Maha\CreateLastname\Model\ResourceModel\AddressRepository" />
</config>

Because in the AccountManagement.php they injected AddressRepositoryInterface in __constructor.

You can achieve this by using plugin as well and that is recommended way.

Related Topic