Ways to Check Current Area Code in Magento 2

Today's tutorial will bring you a guide to check the current area code in Magento 2. This feature is required to develop functionality based on area.

When there is a need to execute the script from the root folder, what are the steps to detect the current area of Magento 2?

There are two methods to check the current area of Magento 2:

  1. Object Manager Method
  2. Construct Method

First of all, Let’s assume that you have already created a module.

1. Object Manager Method:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('Magento\Framework\App\State');
echo $state->getAreaCode(); // Output Like : frontend, backend or webrest_api

Note: Avoid using the object Manager method in your module. Use always construct method.

2. Construct Method:

<?php

namespace MD\Helloworld\Block;

use Magento\Framework\App\State;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;

class AreaCode extends Template
{
    /**
     * @var State
     */
    protected $state;

    /**
     * @param Context $context
     * @param State   $state
     * @param array   $data
     */
    public function __construct (
        Context $context,
        State $state,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->state = $state;
    }

    public function getArea()
    {
        return $this->state->getAreaCode();
    }
}

Now, you can use this block in your layout or construct and get area code by getArea() function.

That’s it !!

Let us know if we missed out on anything. Our experts will be happy to assist you with anything possible.