Override Magento 2 Class using Preference Method.

In Magento, sometimes we have to customize core function and classes. Whenever we have to override or rewrite class( Controller, Block & Model) Magento provides some methods.

1) Preference Method

2) Plugin Method

Override controller using Preference method. Preference overridden all function of the controller if some function is not listed in override controller execute from the original method.

For override some function you have to create a module. For module, creation check Click here.

After creating module Make di.xml file. In module make Panchal\Preference\etc/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\Controller\Account\Create" type="Panchal\Preference\Controller\Account\Create" />
</config>

Now Make override controller in module Panchal\Preference\Controller\Account\Create.php
In controller, we override execute function you can override any function of this class.


<?php
namespace Panchal\Preference\Controller\Account;

class Create extends \Magento\Customer\Controller\Account\Create
{
    public function execute()
    {
		// Add your Logic here ( Restricat Some Country or IP)
		
        if ($this->session->isLoggedIn() || !$this->registration->isAllowed()) {
            /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();
            $resultRedirect->setPath('*/*');
            return $resultRedirect;
        }

        /** @var \Magento\Framework\View\Result\Page $resultPage */
        $resultPage = $this->resultPageFactory->create();
        return $resultPage;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *