Reader Vinai Kopp (of Mage2Katas fame) wrote in with a interesting bit of functionality in the MagentoFrameworkAppState
class we talked about in the Fixing Area code Not Set Exceptions quickie.
Specifically, Vinai had a bit of code that was shared between a command line context, and a web context, and if he tried setting the area code during the web context, Magento would throw a different exception
Area code is already set
That’s because of the following guard clause
#File: vendor/magento/framework/App/State.php
public function setAreaCode($code)
{
if (isset($this->_areaCode)) {
throw new MagentoFrameworkExceptionLocalizedException(
new MagentoFrameworkPhrase('Area code is already set')
);
}
$this->_configScope->setCurrentScope($code);
$this->_areaCode = $code;
}
The MagentoFrameworkAppState
object will only let you set a value once – after that, the area for a specific request/cli-run is immutable. Vinai was kind enough to share his solution
public function __construct(
MagentoFrameworkAppState $appState,
$name=null
) {
try {
$appState->setAreaCode('frontend');
} catch (MagentoFrameworkExceptionLocalizedException $e) {
// intentionally left empty
}
parent::__construct($name);
}
By catching the exception Magento throws and silently ignoring it, Vinai was able to ensure his class/object worked in both a command line context, and in a web context.