For example, I've to override class Magento\Store\Block\Switcher
to Vendor\Module\Block\Switcher
Now I need to add custom method, constructor, and protected variable in upgraded class Vendor\Module\Block\Switcher
.
I've tried following code but it's not working
Add code like below in /etc/frontend/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\Store\Block\Switcher" type="Vendor\Module\Block\Switcher\Index" />
</config>
Add below code in my override class Vendor\Module\Block\Switcher
<?php
namespace Vendor\Module\Block\Switcher;
class Index extends \Magento\Framework\View\Element\Template
{
protected $httpContext; //new variable
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Data\Helper\PostHelper $postDataHelper,
\Magento\Framework\App\Http\Context $httpContext, // Inject New Class Just before Data array if you want to inject
array $data = []
) {
$this->_postDataHelper = $postDataHelper;
$this->httpContext = $httpContext; //New object Get of Injected Class
parent::__construct($context, $data);
}
/**
* Code by devloper
*/
public function isLoggedIn()
{
return (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
}
/**
* Code by developer
*/
public function getBankUrl()
{
if (!$this->isLoggedIn()) {
return '<li class="customer-login"><a href="javascript:void(0);">Bank sd</a></li>';
} else {
return '<li class=""><a href="'.$this->getUrl('rewards/referral').'">Bank</a></li>';
}
}
}
?>