Question

What's the best way to get the current mode Magento 2 is running with code?

In my case it's for a headless Magento, but I can see a number of cases where this might be required.

Was it helpful?

Solution

If you're referring to the deployment mode, you can do it via the CLI using:

php bin/magento deploy:mode:show

If you need to do it via pure code you can use:

protected $_appState;

public function __construct( \Magento\Framework\App\State $appState )
{
    $this->_appState = $appState;
}

public function doSomething() {
    switch ( $this->_appState->getMode() ) {
        case \Magento\Framework\App\State::MODE_DEFAULT:
            // Action for default mode
            break;
        case \Magento\Framework\App\State::MODE_PRODUCTION:
            // Action for production mode
            break;
        case \Magento\Framework\App\State::MODE_DEVELOPER:
            // Action for developer mode
            break;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top