The Magento 2 helper is the class which is used for adding functionalities to several features and can be used anywhere in the entire website. They are created as Singleton (single instances of objects) which can be called in controllers, views, models, templates etc.
So today in this guide, I am going to teach you how to use Magento 2 helper.
Let’s assume that you have to show account login and register links along with the custom phtml file
Create Magento 2 Custom Module
Add module.xml file in app/code/Magenticians/Mymodule/etc
and copy the following code in it:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Magenticians_Mymodule" setup_version="1.0.1">
</module>
</config>
Add registration.php in app/code/Magenticians/Mymodule
and copy the following code in it:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Magenticians_Mymodule',
__DIR__
);
Create Magento 2 Helper
Now add Data.php file in app/code/Magenticians/Mymodule/Helper
and copy the following code in it:
<?php
namespace Magenticians\Mymodule\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
class Data extends AbstractHelper
{
/**
* @var \Magento\Framework\App\Http\Context
*/
private $httpContext;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Framework\App\Http\Context $httpContext
)
{
parent::__construct($context);
$this->httpContext = $httpContext;
}
public function isLoggedIn()
{
$isLoggedIn = $this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
return $isLoggedIn;
}
}
and phtml file how to helper class call
<?php
$helper = $this->helper('Magenticians\Mymodule\Helper\Data');?>
<?php if($helper->isLoggedIn()): ?>
<div class="box-tocart">
<p><a href="<?php echo $block->getUrl('customer/account/login') ?>" title="<?php echo __('Login') ?>"><?php echo __('Login') ?></a> or <a href="<?php echo $block->getUrl('customer/account/create') ?>" title="<?php echo "Register" ?>"><?php echo "Register" ?></a></p>
</div>
<?php endif; ?>