Magento2 观察者模式 之 插件
- etc/di.xml 定义如下:
<type name="Magento\Quote\Model\Quote\Item\ToOrderItem"> <plugin name="McSize_to_order_item" type="Mc\Size\Model\Plugin\Quote\McSizeToOrderItem" sortOrder="1" disabled="false"/> </type>
type name
:输入需要遵循的类或接口的名称。plugin name
:标识插件的任意插件名称。还用于合并插件的配置。plugin type
:填写插件类或其虚拟类型的名称。您可以为此字段引用以下命名约定:\Vendor\Module\Plugin\<ModelName>Plugin
。
- 插件中的3种方法:
before
-before【 Dispatch Class Method Name 】() 在方法以前执行的方法;
around
-around【 Dispatch Class Method Name 】() 在方法运行时;
after
-after【 Dispatch Class Method Name 】() 在方法运行后执行方法;
- 如下实例,将自定义购物车字段 quote_item 表数据,保存到 sales_order_item 的自定义字段;
<?php /** * Created by . * User: jerryxu * Date: 2019/5/5 * Time: 3:48 PM */ namespace Mc\Size\Model\Plugin\Quote; use Mc\Size\Traits\Common; /** * Fixme Plugin Quote_Item_Custom_Field To Sales_Order_Item_Custom_Field * Class McSizeToOrderItem * @package Mc\Size\Model\Plugin\Quote */ class McSizeToOrderItem { /** * */ use Common; /** Fixme texting Debug * @var int * @return 0/1 */ private $log = 1; /**Fixme Overrde Method * @param \Magento\Quote\Model\Quote\Item\ToOrderItem $subject * @param \Closure $proceed * @param \Magento\Quote\Model\Quote\Item\AbstractItem $item * @param array $additional * @return Item */ public function aroundConvert( \Magento\Quote\Model\Quote\Item\ToOrderItem $subject, \Closure $proceed, \Magento\Quote\Model\Quote\Item\AbstractItem $item, $additional = [] ) { /** @var $orderItem Item */ $orderItem = $proceed($item, $additional); $orderItem->setSizeId($item->getSizeId());//Fixme Quote Item Custom Size_id To Sales Order Item Custom Size_id $orderItem->setSizeType($item->setSizeType());//Fixme Quote Item Custom Size_type To Sales Order Item Custom Size_type return $orderItem; } /** Fixme texting Debug * @param \Magento\Quote\Model\Quote\Item\ToOrderItem $subject * @param $data * @return array */ public function beforeConvert(\Magento\Quote\Model\Quote\Item\ToOrderItem $subject, $data) { /** * @var \Mc\Size\Helper\Data $helper */ if($this->log){ $helper = $this->mc_get_obj('Mc\Size\Helper\Data'); $helper->logger(__(__METHOD__)); } } }