Categories


Archives


Recent Posts


Categories


Magento 2: More on Setting Area Codes

astorm

Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

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.

Copyright © Alan Storm 1975 – 2019 All Rights Reserved

Originally Posted: 26th April 2016