Magento 2 Virtual Type

当您运行基于 Magento 2平台的虚拟商店时,真的有必要在Magento 2中使用VirtualType吗?在Magento 2平台上,同时di.xml支持两种类型的节点:节点type和节点virtualtype,而virtualtype不是type。在virtual tape允许插入不同的依赖到现有的类,但不进行任何更改其他类。通过本教程,如何在Magento 2中创建和使用VirtualType

在Magento 2中创建VirtualType

在Magento 2中创建虚拟类型意味着为现有类创建一个子类。所有这些都可以帮助您在Magento 2中创建虚拟类型。

<?php
class OurVirtualTypeName extends \Mageplaza\HelloWorld\Model\Virtualtype
{
}

将以下脚本代码插入到模块中,di.xml以在Magento 2中创建虚拟类型。

#File: app/code/Mageplaza/HelloWorld/etc/di.xml
<config>
    <!-- ... -->
    <virtualType name="ourVirtualTypeName" type="Mageplaza\HelloWorld\Model\Virtualtype">  
    </virtualType>        
</config>

即, 节点放置在主节点下 节点并包括两个属性:名称和类型。尽管name属性通常是该节点的通用特殊名称,但type属性是虚拟类型的真实PHP。

如您所见,对虚拟类型进行一些描述很简单。如果您清除缓存并重复请求,则输出仍然相同。

$ php bin/magento hw:tutorial-virtual-type
First, we'll report on the Mageplaza\HelloWorld\Model\Example object
The Property $property_of_example_object
  is an object
  created with the class: 
  Mageplaza\HelloWorld\Model\Virtualtype

Next, we're going to report on the Example object's one property (an Virtualtype class)
The Property $property_of_argument1_object
  is an object
  created with the class: 
  Mageplaza\HelloWorld\Model\Argument2

Finally, we'll report on an Virtualtype object, instantiated separate from Example
The Property $property_of_argument1_object
  is an object
  created with the class: 
  Mageplaza\HelloWorld\Model\Argument2

在Magento 2中使用虚拟类型

虚拟类型的功能取代了PHP类的位置,您不必使用 如果要自定义注入到Example类的构造函数中的参数,则配置如下。

#File: app/code/Mageplaza/HelloWorld/etc/di.xml    
<config>
    <!-- ... -->
    <virtualType name="ourVirtualTypeName" type="Mageplaza\HelloWorld\Model\Virtualtype">  
    </virtualType>        

    <type name="Mageplaza\HelloWorld\Model\Example">
        <arguments>
            <argument name="the_object" xsi:type="object">Some\Other\Class</argument>
        </arguments>
    </type>        

</config>

但是,即使您已经清理了缓存,应用该命令仍将导致以下错误

$ php bin/magento hw:tutorial-virtual-type

  [ReflectionException]                  
  Class Some\Other\Class does not exist 

让我们使用虚拟类型走向聪明的方式。这意味着Some\Other\Class可以通过ourVirtualTypeName恢复。您可以确保不会导致任何错误,除非您使用上面的命令调用该命令。

#File: app/code/Mageplaza/HelloWorld/etc/di.xml      
<config>
    <!-- ... -->
    <virtualType name="ourVirtualTypeName" type="Mageplaza\HelloWorld\Model\Virtualtype">  
    </virtualType>        

    <type name="Mageplaza\HelloWorld\Model\Example">
        <arguments>
            <argument name="the_object" xsi:type="object">ourVirtualTypeName</argument>
        </arguments>
    </type>        

</config>

感谢您的阅读,希望我们的虚拟类型创建和使用指南使您的业务变得更加完美

赞(0)
微信
支付宝
微信二维码图片

微信扫描二维码打赏

支付宝二维码图片

支付宝扫描二维码打赏

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论