在 Magento 2 中获取商店信息概述

  • 第 1 步:声明Example_HelloWorld
  • 第 2 步:获取phtml文件中的商店信息

第 1 步:声明Example_HelloWorld

您将使用 module 的块类,然后可能在模块的块类的构造函数中Example_HelloWorld注入 的对象。StoreManagerInterface

app/code/Example/HelloWorld/Block/HelloWorld.php

<?php
namespace Example\HelloWorld\Block;
class HelloWorld 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();
    }
    
    /**
     * Get website identifier
     *
     * @return string|int|null
     */
    public function getWebsiteId()
    {
        return $this->_storeManager->getStore()->getWebsiteId();
    }
    
    /**
     * Get Store code
     *
     * @return string
     */
    public function getStoreCode()
    {
        return $this->_storeManager->getStore()->getCode();
    }
    
    /**
     * Get Store name
     *
     * @return string
     */
    public function getStoreName()
    {
        return $this->_storeManager->getStore()->getName();
    }
    
    /**
     * Get current url for store
     *
     * @param bool|string $fromStore Include/Exclude from_store parameter from URL
     * @return string     
     */
    public function getStoreUrl($fromStore = true)
    {
        return $this->_storeManager->getStore()->getCurrentUrl($fromStore);
    }
    
    /**
     * Check if store is active
     *
     * @return boolean
     */
    public function isStoreActive()
    {
        return $this->_storeManager->getStore()->isActive();
    }
}
?>

步骤2:获取.phtml文件中的商店信息

在文件中使用以下脚本.phtml并打印商店信息。

echo $block->getStoreId() . '<br />';
echo $block->getStoreCode() . '<br />';
echo $block->getWebsiteId() . '<br />';
echo $block->getStoreName() . '<br />';
echo $block->getStoreUrl() . '<br />';
echo $block->isStoreActive() . '<br />';