Skip to content

Instantly share code, notes, and snippets.

@6ui11em
Created April 15, 2021 13:26
Show Gist options
  • Save 6ui11em/a472b0c6d7308733d701e4db82c7d32a to your computer and use it in GitHub Desktop.
Save 6ui11em/a472b0c6d7308733d701e4db82c7d32a to your computer and use it in GitHub Desktop.
Magento 2: Emulate Area Code #magento2 #areacode #state #frontend #adminhtml
# File: vendor/magento/framework/App/State.php
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;
}
# Usage
$app_state->emulateAreaCode('adminhtml', function($param1, $param2){
//code that does something `adminhtml` specific here
}, [$param1, $param2]);
# Sample:
# File: vendor/magento/module-customer-sample-data/Model/Customer.php
$this->appState->emulateAreaCode(
'frontend',
[$this->accountManagement, 'createAccount'],
[$customer, $row['password']]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment