Magento 2 get current store
This post is about how to programmatically get current store in Magento 2. If you create a PHP script or Magento 2 module, you may need to check, which store is currently active (calls this script) and for which store you need to get or change values. This is done with the following lines of code…
Magento 2 get current store
You can get current store with every class that injects StoreManagerInterface. From a current store manager you can get all store related information you like. The object is different for each store frontend or even if you call it from backend. This code demonstrates how to create a simple class that injects this store manager interface:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <?php namespace MyCompany\MyModule\Block; class MyModel extends \Magento\Framework\View\Element\Template { protected $_storeManager; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Store\Model\StoreManagerInterface $storeManager, array $data = [] ) { $this->_storeManager = $storeManager; parent::__construct($context, $data); } /** * Get store identifier * * @return int */ public function getStoreId() { return $this->_storeManager->getStore()->getId(); } } |
Method getStoreId() returns id from the current active Magento 2 store.
Different scope
If you want to check if this code was called from adminhtml context you can’t use isAdmin() anymore (this was the common option in Magento 1). If you need to chack this, you can use a method based on \Magento\Framework\App\State class. Inject it and call getAreaCode to get information it this class was called from adminhtml of frontend. A simple if statement for this may look as follows:
1 2 3 | if ($this->state->getAreaCode() == \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE) { // Todo for adminhtml case } |
This checks if area code is equal adminhtml, which is defined as:
1 | const AREA_CODE = 'adminhtml'; |
in \Magento\Backend\App\Area\FrontNameResolver. Everything different than that is frontend scope.
Conclusion
I showed you how to programmatically get current store with Magento 2. If you create Magento 2 modules for multi store environments, this is essential. Different stores may display different product information and may are also using complete different prices for the same products. I also showed you how to check if your code was called from adminhtml or frontend.