请求协助将指定PHP脚本修改为兼容Magento 2版本
Magento 2 版本兼容改造方案
首先纠正原Magento 1脚本的两个核心问题:
- 变量命名错误:实例化的是店铺模型,
$product应改为$store - 逻辑顺序错误:
return $value;写在条件判断之前,导致后续网站ID匹配逻辑永远无法执行
正确的Magento 2实现方式
方式1:推荐使用依赖注入(符合Magento 2开发规范)
在自定义类中通过依赖注入获取店铺仓库服务,避免静态调用:
use Magento\Store\Model\StoreRepository; class YourCustomClass { protected $storeRepository; public function __construct(StoreRepository $storeRepository) { $this->storeRepository = $storeRepository; } public function getCorrespondingCode($order) { $storeId = $order->getStoreId(); try { // 通过店铺ID获取店铺模型 $store = $this->storeRepository->getById($storeId); // 获取关联的网站ID $websiteId = $store->getWebsiteId(); // 根据网站ID返回对应编码 switch ($websiteId) { case 1: return "34501"; case 3: return "34502"; case 2: return "34503"; default: // 处理未匹配场景,返回默认值或空 return ""; } } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { // 捕获店铺不存在的异常 return ""; } } }
方式2:临时脚本/非规范场景使用对象管理器(不推荐生产环境)
如果是临时脚本或无法使用依赖注入的场景,可临时通过对象管理器获取服务:
// 获取对象管理器实例 $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $storeId = $order->getStoreId(); try { $storeRepository = $objectManager->get(\Magento\Store\Model\StoreRepository::class); $store = $storeRepository->getById($storeId); $websiteId = $store->getWebsiteId(); if ($websiteId === 1) { return "34501"; } elseif ($websiteId === 3) { return "34502"; } elseif ($websiteId === 2) { return "34503"; } else { return ""; } } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { return ""; }
关键提示
- Magento 2废弃了
Mage::getModel()这类静态调用,依赖注入是官方推荐的规范写法 - 使用
StoreRepository会自动处理店铺不存在的异常,比直接实例化模型更安全 - 网站ID是整数类型,直接用全等判断比
strpos更准确高效
内容的提问来源于stack exchange,提问作者Hiren
相关产品推荐
相关产品推荐

