Іноді під час кастомізації Magento 2 вам потрібно програмно отримати інформацію про магазин. Вам, можливо, потрібно отримати поточне ID магазину, код магазину, назву, ID веб-сайту або поточну URL-адресу.

Для отримання цих даних використовуйте одиничний екземпляр (singleton instance) наступного класу:

\Magento\Store\Model\StoreManagerInterface

Наприклад, ви можете додати його у свій конструктор класів, а потім викликати:

<?php

namespace \MyCompany\ExampleModule\Model;

class Example
{
private $storeManager;
public function __construct( ... \Magento\Store\Model\StoreManagerInterface $storeManager, ... ) {
... $this->storeManager = $storeManager; ... }     /**
    * Examples
    */
    public function execute()
    {
    /* Get Current Store ID */
      $storeId = $this->storeManager->getStore()->getId();

    /* Get Current Store Code */
       $storeCode = $this->storeManager->getStore()->getCode();

    /* Get Current Store Name */
      $storeName = $this->storeManager->getStore()->getName();

    /* Get Current Store Status */
      $isActive = $this->storeManager->getStore()->isActive();

    /* Get Current Website ID */
$websiteId = $this->storeManager->getStore()->getWebsiteId();

   
/* Get Current URL */
$currentUrl = $this->storeManager->getStore()->getCurrentUrl();

    /* Get Login Page URL */
$loginPageUrl = $this->storeManager->getStore()->getUrl('customer/account/login');

    /* Get Code of Store With ID 2 */
$secondStoreCode = $this->storeManager->getStore(2)->getCode();
    } }

Ви можете використовувати менеджер об’єктів (object manager), щоб швидко отримати об’єкт StoreManager для тесту, як у прикладі нижче:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get(\Magento\Store\Model\StoreManagerInterface::class);

Увага! Якщо ви хочете використовувати StoreManager всередині класу блоків (block class) і блок розширено з \Magento\Framework\View\Element\Template, тоді StoreManager доступний для вас з коробки через захищену властивість $this->_storeManager. Приклад:

<?php

namespace \MyCompany\ExampleModule\Block;

class Example extends \Magento\Framework\View\Element\Template
{

    public function getCurrentStoreId()
    {
    /* Get Current Store ID */
      return $this->_storeManager->getStore()->getId();     } }