How To Get Base URL Magento 2.x Programmatically

There are following below steps need to follow to create Magento 2 custom module to get Base URL, Media URL, Link URL etc,

Step [1] – Create registration.php file under your module [ Namespace / ModuleName ]

File Path=app/code/Mage2db/John/registration.php

Add below content in this file.

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Mage2db_John',
    __DIR__
);

Step [2] – Create module.xml file under your module [ Namespace / ModuleName ]

File Path=app/code/Mage2db/John/etc/module.xml

Add below content in this file.

<?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="Mage2db_John" setup_version="1.0.0" />
</config>

Step [3] – Create routes.xml file under your module etc directory.

Add below content in this file.

File Path=app/code/Mage2db/John/etc/frontend/routes.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
   <router id="standard">
       <route id="john" frontName="john">
         <module name="Mage2db_John" />
       </route>
   </router>
</config>

Step [4] – Create Controller under your module.

Add below content in this file.

File Path=app/code/Mage2db/John/Controller/Index/Index.php

<?php
namespace Mage2db\John\Controller\Index;

use Magento\Backend\App\Action\Context;

class Index extends \Magento\Framework\App\Action\Action
{
	
    /**
     * @var \Magento\Framework\App\Cache\TypeListInterface
     */
    protected $_cacheTypeList;

    /**
     * @var \Magento\Framework\App\Cache\StateInterface
     */
    protected $_cacheState;

    /**
     * @var \Magento\Framework\App\Cache\Frontend\Pool
     */
    protected $_cacheFrontendPool;

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;
	

    /**
     * @param Action\Context $context
     * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
     * @param \Magento\Framework\App\Cache\StateInterface $cacheState
     * @param \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    public function __construct(
       \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
        \Magento\Framework\App\Cache\StateInterface $cacheState,
        \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
				
    ) {
        parent::__construct($context);
        $this->_cacheTypeList = $cacheTypeList;
        $this->_cacheState = $cacheState;
        $this->_cacheFrontendPool = $cacheFrontendPool;
        $this->resultPageFactory = $resultPageFactory;
        $this->_messageManager = $messageManager;
				
     }
    
    /**
     * Flush cache storage
     *
     */
    public function execute()
    {
	    $this->resultPage = $this->resultPageFactory->create();  
        return $this->resultPage;
    }
}

Step [5] – Create Helper.php under your module.

Add below content in this file.

File Path=app/code/Mage2db/John/Helper/Data.php

<?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);
    }
}

Step [6] – Create Block under your module.

Add below content in this file.

app/code/Mage2db/John/Block/Index/Index.php

<?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);
    }
	  
}

Step [7] – Create view under your module.

under view folder create layout & template file

Layout File

app/code/Mage2db/John/view/frontend/layout/john_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
 <body>		
   <referenceContainer name="main.content">			
<block class="Mage2db\John\Block\Index\Index" name="index_index" template="index/index.phtml"> </block>
  </referenceContainer>      
 </body>
</page>

Template File

app/code/Mage2db/John/view/frontend/templates/index/index.phtml

<?php

   //Template index phtml 
  echo"<BR> Base URL===".$baseurl= $block->getbaseurldata();
        
?>		

Step [8] – Finally your custom module for Base URL, Media URL, Link URL etc . has been created

Run the following below commands at your Magento 2 root directory

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento indexer:reindex
php bin/magento cache:clean
php bin/magento cache:flush

Run below URL

https://mage2db.com/john/index/index

Leave a Reply

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