Magento 2:如何通过Observer中的网站ID获取网站URL

时间:2016-01-02 05:53:43

标签: php magento magento2

我的magento 2商店有多个网站。 我正在创建自定义代码,所以我需要使用网站ID网站网址,我尝试了很多不同的方式,但我不能得到网址。

$this->_objectManager->getWebsite(1)->getDefaultStore()->getBaseUrl();

我也在尝试另一种方式:

 public function __construct(
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
    \Linksture\ApplyCoupon\Model\ApplyCouponFactory $applycouponFactory,
    \Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory $collectionFactory,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\SalesRule\Model\ResourceModel\Coupon\CollectionFactory $couponcollectionFactory
    ) {
$this->_scopeConfig = $scopeConfig;
$this->_applycouponFactory = $applycouponFactory;
$this->_collectionFactory = $collectionFactory;
$this->_storeManager = $storeManager;
$this->_couponcollectionFactory = $couponcollectionFactory;
}

public function execute(\Magento\Framework\Event\Observer $observer)
{  
    echo $this->_storeManager->getWebsite(1)->getDefaultStore()->getBaseUrl();
}

在magento 1.x中,使用如下所示。

Mage::app()->getWebsite(1)->getDefaultStore()->getBaseUrl();

1 个答案:

答案 0 :(得分:2)

假设您有多个网站和多个商店下的一个网站,您将获得所有 baseUrl websiteId storeId

 public function __construct(
            \Magento\Framework\ObjectManagerInterface $objectManager    
        ) {
            $this->_objectManager = $objectManager;
        }

        public function execute(\Magento\Framework\Event\Observer $observer){
            $storeManager =  $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface'); 
            $websites = $storeManager->getWebsites();
            foreach($websites as $website){
                foreach($website->getStores() as $store){
                    $wedsiteId = $website->getId();
                    $storeObj = $storeManager->getStore($store);
                    $storeId = $storeObj->getId();
                    $url = $storeObj->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);
                }
            }

        }