Context : I'm coding a lot of CLI commands and I noticed most of the time if I don't set what store I'm operating on, it will counter-intuitively be set to the first non-global store. Since more often than not I need to operate on the global store (aka \Magento\Store\Model\Store::DEFAULT_STORE_ID) I have begun setting the current store at the beginning of my scripts.

As far as I know there are two different ways to set the current store in Magento 2 : One is using the \Magento\Store\Model\StoreManager and the other one is using \Magento\Store\Model\App\Emulation.

Question : Which method is considered best practice for environment initialisation?

Thank you guys. :)


I'd say the method \Magento\Store\Model\App\Emulation is better.

--> this method is used when sending emails; it ensures the below are setup to clone the store preferences in 3 ways:

  • theme

  • store preference (config)

  • locale used

Now, it is also common to only set the area code: with the object \Magento\Framework\App\State $state (eg: $this->state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);)

this will give your script privileges to save entities that are restricted to be saved in backend for instance.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.