Skip to main content
3 of 3
deleted 184 characters in body
Rakesh Donga
  • 5.4k
  • 2
  • 25
  • 57

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.

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 observer file how to helper class call

<?php

namespace Magenticians\Mymodule\Observer;

use Magento\Framework\Event\ObserverInterface;

class Mymodulename implements ObserverInterface
{
    ...

    protected $dataHelper;

    ...

    public function __construct(
        ...
        \Magenticians\Mymodule\Helper\Data $dataHelper
        ...
    ) {
        ...
        $this->dataHelper = $dataHelper;
        ...
    }

    public function ...(){
        $helper = $this->dataHelper->isLoggedIn();
    }

    ...
}

?>
Rakesh Donga
  • 5.4k
  • 2
  • 25
  • 57