Magento 2.x Use of Helper File of Module

Magento 2 module helper file used to include common method those are using in multiple places of that module.

Create Helper.php under your module.

Add below content in this file.

File Path=app/code/VendorName/ModuleName/Helper/Data.php

VendorName=Mage2db and ModuleName=John

<?php
namespace  Mage2db\John\Helper;
use Magento\Store\Model\StoreManagerInterface;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
	protected $storeManager; 

	/**
     * @param \Magento\Framework\App\Helper\Context $context
     */
	public function __construct
	(
   \Magento\Framework\App\Helper\Context $context,   StoreManagerInterface $storeManager
	) 
	{
	    $this->storeManager = $storeManager;	
		parent::__construct($context);
	}
	  
	public function getStoreManagerData()
    {
          //return $storeUrl = $this->storeManager->getStore()->getBaseUrl();
         // get Store Url without index.php
        return $storeUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);
           // get Link Url of store
          // $storeLinkUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_DIRECT_LINK);
         // get media Base Url
        //  $storeMediaUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
      // get Static content Url
      // $storeStaticUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC);
    }
}

in above Helper/Data.php , we have defined getStoreManagerData()

By using below code, anywhere inside module we can use getStoreManagerData()

$this->helperData->getStoreManagerData();

Finally once all command method defined inside Helper/Data.php, we can use anywhere inside module.

Leave a Reply

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