17

I want to check whether it is front or backend.
How can I do that?

5 Answers 5

36

Read More: blog.mageprince.com

With objectManager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$state =  $objectManager->get('Magento\Framework\App\State');
echo $state->getAreaCode(); //frontend or adminhtml or webapi_rest

With Dependency Injection

protected $_state;

public function __construct (
    \Magento\Framework\App\State $state
) {
    $this->_state = $state;
}

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

Note: As per magento2 coding standards don't use object manager instance directly in files

2
  • +1 @PЯINCƏ As per Magento coding standard, Don't use full class name in construct method. Declare full class using the use statement and declare only class name to construct() method. Commented Aug 22, 2019 at 12:48
  • 1
    @RakeshJesadiya Im not agree with you, please see this question : magento.stackexchange.com/questions/106096/…
    – PЯINCƎ
    Commented Aug 22, 2019 at 12:55
13

People have answered the question already. I am just making it better.

const AREA_CODE = \Magento\Framework\App\Area::AREA_ADMINHTML;

private $_state;

public function __construct (
    \Magento\Framework\App\State $state
) {
    $this->_state = $state;
}

public function isAdmin()
{
    $areaCode = $this->_state->getAreaCode();
    return $areaCode == self::AREA_CODE;
}
2
  • hi @dinesh, can we enable maintainance mode only for admin side? Commented Mar 24, 2020 at 12:16
  • No, that option is not available. Commented Mar 24, 2020 at 13:37
6

Use below code

$objectmanager = \Magento\Framework\App\ObjectManager::getInstance();
$state =  $objectmanager->get('Magento\Framework\App\State');
if($state->getAreaCode() == 'frontend')
  //frontend
else
  //backend

Edit : In some cases ( for example shipping calculation ) area code returns "webapi_rest", not "frontend" on frontend side.

1
  • So both frontend and backend can produce calls that come in with webapi_rest, yet your code example still assumes that anything that isn't frontend MUST be backend. Commented Jul 6, 2022 at 7:36
2

Try code below for check if you are in admin area

function df_is_admin($store = null) {
    /** @var \Magento\Framework\ObjectManagerInterface $om */
    $om = \Magento\Framework\App\ObjectManager::getInstance();
    /** @var \Magento\Framework\App\State $state */
    $state =  $om->get('Magento\Framework\App\State');
    return 'adminhtml' === $state->getAreaCode();
}
0
 public function isAdmin(){
      return ('adminhtml' == $this->_state->getAreaCode());
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.