According to Magento 2 documentation to use object manager is not recommend. But in some cases this method can be very useful and time saver. I am always using it in my temporary code, when I am debugging or testing something. It is short, in one piece and you can put this code snippet almost everywhere in Magento code, including .phtml templates.
Code snippet to get current store id
$storeId = \Magento\Framework\App\ObjectManager::getInstance()
->get(\Magento\Store\Model\StoreManagerInterface::class)
->getStore()
->getId();
and store name
$storeName = \Magento\Framework\App\ObjectManager::getInstance()
->get(\Magento\Store\Model\StoreManagerInterface::class)
->getStore()
->getName();
Getting store information by store ID
The code snippet above gives you current store information, but in some cases you might need to get store name or other store information by store ID.
Lets say we already have store id from $order object
$storeId = $order->getStoreId();
then to get store name by store id
$storeName = \Magento\Framework\App\ObjectManager::getInstance()
->get(\Magento\Store\Model\StoreManagerInterface::class)
->getStore($storeId)
->getName();
So in general, if you will pass a store ID to method getStore, it loads specific store and returns information by store id, otherwise, it returns you current store information.
Right way to get store information
Okay, then you probably can ask, what is the right way to get information, if the object manager way is not recommended? The answer – dependency injection method. Using this method, StoreManager class has to be included via class constructor. Here is the simple example, how to get current store id and name using dependency injection.
public $storeManager;
public function __construct(
. . .
\Magento\Store\Model\StoreManagerInterface $storeManager
. . .
) {
. . .
$this->storeManager = $storeManager;
. . .
}
and then to get store id
$storeId = $this->storeManager->getStore()->getId();
or to get store name
$storeName = $this->storeManager->getStore()->getName();
Troubleshooting
No changes in frontend
If you have added the object manager code snippet in .phtml template file and can’t see any changes in fronted, probably it will be related to cache. You need to clear it.
Conclusion
In case, it is not a temporary code and you know how – use dependency injection method to get store information.
That’s all for this post. Let me know in the comments bellow, if you had some questions, or had some problems using these code snippets. I will be more than happy to append this post with your case.
Happy coding guys!