Hi everyone, Today I will guide you how to get current AREA CODE in Magento 2.
You can get area code using below 2 methods..
1. Directly using Object Manager
Sometimes, you need to create root scripts to perform some operations, and you want to perform that actions for specific area like frontend or backend. So you can put condition of area code..
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('Magento\Framework\App\State');
echo $state->getAreaCode();
2. Using Helper/Block class
You can get Area code by injecting Magento\Framework\App\State class in your Block or Helper class, this is best practices avoid to use object manager and inject in constructor and use them.
<?php
namespace Magepow\Module\Block;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\App\State;
class Index extends Template
{
protected $state;
public function __construct(
Context $context,
State $state
array $data = []
) {
parent::__construct($context, $data);
$this->state = $state;
}
public function getAreaCode()
{
return $this->state->getAreaCode();
}
}
Now, you can use this getAreaCode() function to get area code, you can inject above class in your any Block file.
If your website is having problems, please leave a comment below or contact us at Magepow Contact, the Magepow technician team will assist in solving your problem quickly. Thanks.
Hope this article will helpful for you!
Leave a Reply