Emulating Areas in Magento 2

Sometimes while running the installer script, we get the error as "Area code is not set".
To resolve that we sometimes use following code snippet directly which is not a good practice.


Note: We can the following areas in Magento which are listed in "Magento\Framework\App\Area" class as below:
const AREA_GLOBAL = 'global';
const AREA_FRONTEND = 'frontend';
const AREA_ADMINHTML = 'adminhtml';
const AREA_DOC = 'doc';
const AREA_CRONTAB = 'crontab';
const AREA_WEBAPI_REST = 'webapi_rest';
const AREA_WEBAPI_SOAP = 'webapi_soap';

We should use the standard emulateAreaCode() method provided by Magento to emulate the area defined in "Magento\Framework\App\State" class as below.

public function emulateAreaCode($areaCode, $callback, $params = [])
    $currentArea = $this->_areaCode;
    $this->_areaCode = $areaCode;
    $this->_isAreaCodeEmulated = true;
    try {
        $result = call_user_func_array($callback, $params);
    } catch (\Exception $e) {
        $this->_areaCode = $currentArea;
        $this->_isAreaCodeEmulated = false;
        throw $e;
    $this->_areaCode = $currentArea;
    $this->_isAreaCodeEmulated = false;
    return $result;

You can find the use of the emulateAreaCode() method in below Magento core file location.
File Location: vendor/magento/module-customer-sample-data/Model/Customer.php

[$this->accountManagement, 'createAccount'],
[$customer, $row['password']]

Hope this is helpful!

Leave a Reply