Magento 2:如何覆盖Configurable.php?

在magento 2中,使用PreferenceConfigurable.php文件不是简单地覆盖,这是magento 2错误吗?

我仅在di.xml文件中使用首选项方法进行了覆盖,但没有覆盖。

我想function getJsonConfig()从文件中覆盖。仅使用magento 2的Simply Override方法。di.xml文件代码

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\ConfigurableProduct\Block\Product\View\Type\Configurable" type="Package\Configurable\Block\Product\View\Type\Configurable"/>    
</config>

有什么技巧或方法可以覆盖Configurable.php文件吗?

回答:

VendorName/ModuleName/etc/frontend/di.xml


<?xml version="1.0"?>

    <type name="Magento\ConfigurableProduct\Block\Product\View\Type\Configurable">
        <plugin name="vendor_configurable_product_configurable" type="VendorName\ModuleName\Block\ConfigurableProduct\Product\View\Type\Configurable" sortOrder="1"/>
    </type>
</config>

namespace VendorName\Module\Block\ConfigurableProduct\Product\View\Type;

use Magento\Framework\Json\EncoderInterface;
use Magento\Framework\Json\DecoderInterface;
class Configurable
{

    protected $jsonEncoder;
    protected $jsonDecoder;

    public function __construct(
        EncoderInterface $jsonEncoder,
        DecoderInterface $jsonDecoder
    ) {

        $this->jsonDecoder = $jsonDecoder;
        $this->jsonEncoder = $jsonEncoder;
    }

    public function aroundGetJsonConfig(
        \Magento\ConfigurableProduct\Block\Product\View\Type\Configurable $subject,
        \Closure $proceed
    )
    {
        $config = $proceed();
        $config = $this->jsonDecoder->decode($config);
        $config['url'] = 'sample_url';
        return $this->jsonEncoder->encode($config);
    }
}

You can use after plugin following way:


namespace VendorName\Module\Block\ConfigurableProduct\Product\View\Type;

use Magento\Framework\Json\EncoderInterface;
use Magento\Framework\Json\DecoderInterface;
class Configurable
{

    protected $jsonEncoder;
    protected $jsonDecoder;

    public function __construct(
        EncoderInterface $jsonEncoder,
        DecoderInterface $jsonDecoder
    ) {

        $this->jsonDecoder = $jsonDecoder;
        $this->jsonEncoder = $jsonEncoder;
    }

    public function afterGetJsonConfig(
        \Magento\ConfigurableProduct\Block\Product\View\Type\Configurable $subject,
        $config
    )
    {
        $config = $this->jsonDecoder->decode($config);
        $config['url'] = 'sample_url';
        return $this->jsonEncoder->encode($config);
    }
}

相关文章

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