系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》
本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。
在Magento 2中获取所有网站的所有商店的步骤:
步骤1:转到以下文件路径
app\code\Vendor\Extension\etc\di.xml
然后添加代码,如下所示
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Magento\Store\Block\Switcher" type="Vendor\Extension\Block\Switcher"/> </config>
步骤2:现在移动到以下文件路径
app\code\Vendor\Extension\Block\Switcher.php
之后添加以下代码片段
<?php namespace Vendor\Extension\Block; use Magento\Directory\Helper\Data; use Magento\Store\Model\Group; use Magento\Store\Model\Store; use Magento\Framework\App\ActionInterface; use Magento\Framework\App\ObjectManager; use Magento\Framework\Url\Helper\Data as UrlHelper; /** * Switcher block * * @api * @since 100.0.2 */ class Switcher extends \Magento\Store\Block\Switcher { /** * @var bool */ protected $_storeInUrl; /** * @var \Magento\Framework\Data\Helper\PostHelper */ protected $_postDataHelper; /** * @var UrlHelper */ private $urlHelper; /** * @param \Magento\Framework\View\Element\Template\Context $context * @param \Magento\Framework\Data\Helper\PostHelper $postDataHelper * @param array $data * @param UrlHelper $urlHelper */ public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\Data\Helper\PostHelper $postDataHelper, array $data = [], \Magento\Framework\Url\Helper\Data $urlHelper = null ) { $this->_postDataHelper = $postDataHelper; parent::__construct($context, $postDataHelper, $data); $this->urlHelper = $urlHelper ?: ObjectManager::getInstance()->get(\Magento\Framework\Url\Helper\Data::class); } /** * @return array */ public function getRawAllStores() { $websites = $this->_storeManager->getWebsites(); $stores = []; foreach ($websites as $website) { $websiteStores = $website->getStores(); foreach ($websiteStores as $store) { /* @var $store \Magento\Store\Model\Store */ if (!$store->isActive()) { // continue; } $localeCode = $this->_scopeConfig->getValue( Data::XML_PATH_DEFAULT_LOCALE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store ); $store->setLocaleCode($localeCode); $params = ['_query' => []]; if (!$this->isStoreInUrl()) { $params['_query']['___store'] = $store->getCode(); } $baseUrl = $store->getUrl('', $params); $store->setHomeUrl($baseUrl); $stores[$store->getGroupId()][$store->getId()] = $store; } } return $stores; } }
步骤3:最后,运行以下命令
php bin/magento setup:di:compile php bin/magento cache:flush
结论:
因此,借助此方法,您可以获取Magento 2商店所有网站的所有商店列表。