目标:
1. 自定义字段。
2. 启用新商品类型简化商品属性。
3. 能够对接自定义商品后续处理过程。
参考:Magento_Downloadable 模块
博文状态:持续编辑中...
简单教程:通过模块开发自定义商品类型
忽略部分,如何创建一个模块,并启用(这个部分可以看我的其它博文)。
关键过程:
1. 创建 MODULE/etc/product_types.xml, 内容可参考Magento_Downloadable.
2. 在该XML文件中,需要指定“modelInstance” 这个是定制商品类型的“类型实例”(在Magento2.x系统中,商品服务、商品Model、商品内容类型Model都各不相同,商品的内容类型Model就是“类型实例”)。
3. modelInstance="YOURVENDORYOURMODULEModelProductType"基本内容:
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Mdu\Service\Model\Product;
use \Magento\Catalog\Api\ProductRepositoryInterface;
use \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface;
/**
* Downloadable product type model
*
* @api
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @since 100.0.2
*/
class Type extends \Magento\Catalog\Model\Product\Type\Virtual{
}
可以看到我整篇代码复制Downloadable模块下面的,只自定义了一下namespace.这样就可以了。
4. 更新代码,更新Magento缓存,服务器命令行执行:
php -f Magento_ROOT/bin/magento setup:upgrade
5. 结果,这时你在后台添加商品时已经可以选择刚刚创建的商品类型。如下图:
完成,剩下的是自定义字段部分。
代码跟踪与研究过程
<!-- 这个是MODULE/etc/product_types.xml 商品类型添加核心文件 -->
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Catalog:etc/product_types.xsd">
<type name="downloadable" label="Downloadable Product" modelInstance="Magento\Downloadable\Model\Product\Type" composite="false" isQty="true" canUseQtyDecimals="false" sortOrder="60">
<priceModel instance="Magento\Downloadable\Model\Product\Price" />
<indexerModel instance="Magento\Downloadable\Model\ResourceModel\Indexer\Price" />
<customAttributes>
<attribute name="refundable" value="false"/>
<attribute name="is_real_product" value="false"/>
</customAttributes>
</type>
<composableTypes>
<type name="downloadable" />
</composableTypes>
</config>
其中: modelInstance="MagentoDownloadableModelProductType" 这个是重点,Magento系统的模块结构有些混乱,架构和业务模块,至少在目录结构级别是混合的。
在商品类型定义这里,系统依然是直接对接 Magento_Catalog/Product, 进而由这个Model来对接自定义商品相关操作。
吐槽一下:Magento2.x 的Model体系使用有些混乱,兼顾数据模型、业务服务、甚至还包括一些模版渲染的工作。
下面是代码跟踪测试记录:
执行结果:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[2018-03-23 02:35:05] Magento\Catalog\Model\Product::getAttributes - 813
127.0.0.1
----------
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
string(39) "Magento\Downloadable\Model\Product\Type"
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。