【问题标题】:Magento 2 - di.xml virtual type - overriding a classMagento 2 - di.xml 虚拟类型 - 覆盖一个类
【发布时间】:2017-04-13 19:59:06
【问题描述】:

我有一个覆盖 ShippingMethodConverter 类的模块。我在 di.xml 中进行了这样的配置:

<preference for="Magento\Quote\Model\Cart\ShippingMethodConverter"
            type="MyNameSpace\MyModule\Quote\Model\Cart\ShippingMethodConverter"/>                                

<virtualType name="mynamespace_mymodule_quote_mode_cart_shippingmethodconverter" type="\MyNameSpace\MyModule\Quote\Model\Cart\ShippingMethodConverter">
    <arguments>
        <argument name="shippingMethodConverter" xsi:type="object">\Magento\Quote\Model\Cart\ShippingMethodConverter</argument>
    </arguments>
</virtualType>

不幸的是,我收到了以下错误:

1 exception(s):
Exception #0 (Exception): Recoverable Error: Argument 2 passed to 
Magento\Quote\Model\ShippingMethodManagement::__construct() 
must be an instance of Magento\Quote\Model\Cart\ShippingMethodConverter, 
instance of MyNameSpace\MyModule\Quote\Model\Cart\ShippingMethodConverter given, 
called in /path_to_magento/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php 
on line 93 and defined in 
/path_to_magento/vendor/magento/module-quote/Model/ShippingMethodManagement.php on line 62

我的课是这样开始的:

namespace MyNameSpace\MyModule\Quote\Model\Cart;

/**
 * Quote shipping method data.
 *
 */
class ShippingMethodConverter
{
..

根据我对 virtualType 的正确理解,我想说我的类应该像给定参数一样处理,以保证 magento 核心中没有类型解析错误。

【问题讨论】:

    标签: php xml magento magento2


    【解决方案1】:

    您看到的错误是基于此

    <preference for="Magento\Quote\Model\Cart\ShippingMethodConverter"
                type="MyNameSpace\MyModule\Quote\Model\Cart\ShippingMethodConverter"/>
    

    通过这个配置,你告诉 Magento 的自动构造函数依赖注入系统,每当它在构造函数中看到 Magento\Quote\Model\Cart\ShippingMethodConverter 时,它应该实例化一个 MyNameSpace\MyModule\Quote\Model\Cart\ShippingMethodConverter 对象而不是 Magento\Quote\Model\Cart\ShippingMethodConverter 对象。

    Magento 正确地执行了此操作,但由于您的对象未能通过构造函数中的类型提示检查,PHP 因错误而退出。你的类需要扩展Magento\Quote\Model\Cart\ShippingMethodConverter类(或者如果Magento\Quote\Model\Cart\ShippingMethodConverter是一个接口就实现它)

    【讨论】:

    • 感谢您的回答。知道它适用于 ShippingMethodConverter。我还有一个关于我想要覆盖的界面的问题。因为我收到以下错误:无法实例化接口 MyNameSpace\MyModule\Quote\Api\Data\ShippingMethodInterface。正如我正确理解的那样,我只能为虚拟类型分配一个类而不是一个接口。或者它如何与接口一起工作?提前谢谢你
    • @StephanHofmann 恐怕这有点太模糊了,我无法 100% 肯定地回答,但听起来您的配置正在尝试实例化一个接口。你需要为你的接口创建一个&lt;preference&gt;,告诉Magento在遇到MyNameSpace\MyModule\Quote\Api\Data\ShippingMethodInterface时应该实例化哪个具体类
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    相关资源
    最近更新 更多